Konwertuj uniksowy znacznik czasu na czas w JavaScript

Przechowuję czas w bazie danych MySQL jako uniksowy znacznik czasu, który jest wysyłany do jakiegoś kodu JavaScript. Jak miałbym to wykorzystać?

Na przykład w formacie HH / MM / SS.

Author: John Slegers, 2009-05-11

23 answers

// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();

// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

Aby uzyskać więcej informacji na temat obiektu Date, zapoznaj się ze specyfikacją MDN lub specyfikacją ECMAScript 5.

 1335
Author: Aron Rotteveel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-05 17:49:36

function timeConverter(UNIX_timestamp){
  var a = new Date(UNIX_timestamp * 1000);
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var year = a.getFullYear();
  var month = months[a.getMonth()];
  var date = a.getDate();
  var hour = a.getHours();
  var min = a.getMinutes();
  var sec = a.getSeconds();
  var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
  return time;
}
console.log(timeConverter(0));
 238
Author: shomrat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-12 12:09:08

JavaScript działa w milisekundach, więc najpierw musisz przekonwertować znacznik czasu Uniksa z sekund na milisekundy.

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...
 142
Author: Steve Harrison,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-25 11:30:33

Jestem zwolennikiem Jacoba Wrighta.Date.format() biblioteka, która implementuje JavaScript formatowanie daty w stylu PHP date() Funkcja.

new Date(unix_timestamp * 1000).format('h:i:s')
 72
Author: Brad Koch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-16 20:35:18

Oto najkrótsze rozwiązanie Jednowierszowe do sformatowania sekund jako hh:mm:ss:

/**
 * Convert seconds to time string (hh:mm:ss).
 *
 * @param Number s
 *
 * @return String
 */
function time(s) {
    return new Date(s * 1e3).toISOString().slice(-13, -5);
}

console.log( time(12345) );  // "03:25:45"

Metoda Date.prototype.toISOString() zwraca czas w uproszczony Rozszerzony ISO 8601 format, który ma zawsze 24 lub 27 znaków (tj. YYYY-MM-DDTHH:mm:ss.sssZ lub ±YYYYYY-MM-DDTHH:mm:ss.sssZ odpowiednio). Strefa czasowa jest zawsze zero UTC offset.

Uwaga: rozwiązanie to nie wymaga żadnych bibliotek innych firm i jest obsługiwane we wszystkich nowoczesnych przeglądarkach i JavaScript silniki.

 41
Author: VisioN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-10 14:14:16

Pomyślałbym o użyciu biblioteki takiej jak momentjs.com , to sprawia, że to naprawdę proste:

Oparty na uniksowym znaczniku czasu:

var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );

Na podstawie MySQL date string:

var now = moment("2010-10-10 12:03:15");
console.log( now.format("HH/mm/ss") );
 24
Author: homtg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-05 17:53:52

Użycie:

var s = new Date(1504095567183).toLocaleDateString("en-US")
// expected output "8/30/2017"   

I na czas:

var s = new Date(1504095567183).toLocaleTimeString("en-US") 
// expected output "3:19:27 PM"`

Patrz Data.prototyp.toLocaleDateString()

 21
Author: Dan Alboteanu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-12 09:19:25

UNIX timestamp to liczba sekund od 00:00:00 UTC 1 stycznia 1970 (według Wikipedii ).

Argumentem obiektu Date w Javascript jest Liczba milisekund od 00:00:00 UTC 1 stycznia 1970 (zgodnie z W3Schools dokumentacja Javascript).

Patrz kod poniżej na przykład:

    function tm(unix_tm) {
        var dt = new Date(unix_tm*1000);
        document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');

    }

tm(60);
tm(86400);

Daje:

1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)
 20
Author: Grzegorz Gierlik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-17 09:20:17

Używając Chwili.js , możesz uzyskać czas i datę w następujący sposób:

var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");

I możesz uzyskać tylko czas używając tego:

var timeString = moment(1439198499).format("HH:mm:ss");
 16
Author: Peter T.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-05 18:01:14

Problem z wyżej wymienionymi rozwiązaniami polega na tym, że jeśli godzina, minuta lub sekunda ma tylko jedną cyfrę (tj. 0-9), czas byłby zły, np. może być 2:3:9, ale raczej 02:03:09.

Zgodnie z ta strona wydaje się być lepszym rozwiązaniem, aby użyć metody "toLocaleTimeString" Date.

 14
Author: Bernie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-01 19:11:18

Inny sposób-z ISO 8601 Data.

var timestamp = 1293683278;
var date = new Date(timestamp*1000);
var iso = date.toISOString().match(/(\d{2}:\d{2}:\d{2})/)
alert(iso[1]);
 13
Author: deadrunk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-05 17:53:09

W momencie musisz użyć unix timestamp:

var dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");
 13
Author: Valix85,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-24 13:21:04

Nowoczesne rozwiązanie, które nie wymaga biblioteki 40 KB:

Intl.DateTimeFormat jest niekulturalnym imperialistycznym sposobem formatowania daty/czasu.

// Setup once
var options = {
    //weekday: 'long',
    //month: 'short',
    //year: 'numeric',
    //day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
},
intlDate = new Intl.DateTimeFormat( undefined, options );

// Reusable formatter
var timeStamp = 1412743273;
console.log( intlDate.format( new Date( 1000 * timeStamp ) ) );
 8
Author: Adria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-05 17:55:42

Bazując na odpowiedzi @shomrat, oto fragment, który automatycznie zapisuje datetime w ten sposób (nieco podobny do daty StackOverflow dla odpowiedzi: answered Nov 6 '16 at 11:51):

today, 11:23

Lub

yersterday, 11:23

Or (if different but same year than today)

6 Nov, 11:23

Or (if another year than today)

6 Nov 2016, 11:23

function timeConverter(t) {     
    var a = new Date(t * 1000);
    var today = new Date();
    var yesterday = new Date(Date.now() - 86400000);
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var hour = a.getHours();
    var min = a.getMinutes();
    if (a.setHours(0,0,0,0) == today.setHours(0,0,0,0))
        return 'today, ' + hour + ':' + min;
    else if (a.setHours(0,0,0,0) == yesterday.setHours(0,0,0,0))
        return 'yesterday, ' + hour + ':' + min;
    else if (year == today.getFullYear())
        return date + ' ' + month + ', ' + hour + ':' + min;
    else
        return date + ' ' + month + ' ' + year + ', ' + hour + ':' + min;
}
 7
Author: Basj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-12 12:14:25
// Format value as two digits 0 => 00, 1 => 01
function twoDigits(value) {
   if(value < 10) {
    return '0' + value;
   }
   return value;
}

var date = new Date(unix_timestamp*1000);
// display in format HH:MM:SS
var formattedTime = twoDigits(date.getHours()) 
      + ':' + twoDigits(date.getMinutes()) 
      + ':' + twoDigits(date.getSeconds());
 5
Author: Fireblaze,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-04 15:34:32

Zwróć uwagę na problem zerowy z niektórymi odpowiedziami. Na przykład znacznik czasu 1439329773 zostanie omyłkowo zamieniony na 12/08/2015 0:49.

Sugerowałbym użycie następujących sposobów, aby rozwiązać ten problem:

var timestamp = 1439329773; // replace your timestamp
var date = new Date(timestamp * 1000);
var formattedDate = ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
console.log(formattedDate);

Teraz daje:

12/08/2015 00:49
 5
Author: TechWisdom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-11 22:09:32
function getTIMESTAMP() {
      var date = new Date();
      var year = date.getFullYear();
      var month = ("0"+(date.getMonth()+1)).substr(-2);
      var day = ("0"+date.getDate()).substr(-2);
      var hour = ("0"+date.getHours()).substr(-2);
      var minutes = ("0"+date.getMinutes()).substr(-2);
      var seconds = ("0"+date.getSeconds()).substr(-2);

      return year+"-"+month+"-"+day+" "+hour+":"+minutes+":"+seconds;
    }
//2016-01-14 02:40:01
 5
Author: synan54,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-14 00:43:34

Zobacz Konwerter Daty / Epoki.

MusiszParseInt, inaczej by to nie zadziałało:


if (!window.a)
    window.a = new Date();

var mEpoch = parseInt(UNIX_timestamp);

if (mEpoch < 10000000000)
    mEpoch *= 1000;

------
a.setTime(mEpoch);
var year = a.getFullYear();
...
return time;
 4
Author: shams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-05 17:51:45

Możesz użyć następującej funkcji do konwersji znacznika czasu na format HH:MM:SS:

var convertTime = function(timestamp, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    var date = timestamp ? new Date(timestamp * 1000) : new Date();
    return [
        pad(date.getHours()),
        pad(date.getMinutes()),
        pad(date.getSeconds())
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

Bez podania separatora, używa : jako (domyślnego) separatora:

time = convertTime(1061351153); // --> OUTPUT = 05:45:53

Jeśli chcesz użyć / jako separatora, po prostu podaj go jako drugi parametr:

time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55

Demo

var convertTime = function(timestamp, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    var date = timestamp ? new Date(timestamp * 1000) : new Date();
    return [
        pad(date.getHours()),
        pad(date.getMinutes()),
        pad(date.getSeconds())
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

document.body.innerHTML = '<pre>' + JSON.stringify({
    920535115 : convertTime(920535115, '/'),
    1061351153 : convertTime(1061351153, ':'),
    1435651350 : convertTime(1435651350, '-'),
    1487938926 : convertTime(1487938926),
    1555135551 : convertTime(1555135551, '.')
}, null, '\t') +  '</pre>';
[[7]}Zobacz this Fiddle.
 4
Author: John Slegers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-24 12:42:02
function timeConverter(UNIX_timestamp){
 var a = new Date(UNIX_timestamp*1000);
     var hour = a.getUTCHours();
     var min = a.getUTCMinutes();
     var sec = a.getUTCSeconds();
     var time = hour+':'+min+':'+sec ;
     return time;
 }
 2
Author: shomrat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-21 00:54:49

Jeśli chcesz przekonwertować czas trwania Unix na rzeczywiste godziny, minuty i sekundy, możesz użyć następującego kodu:

var hours = Math.floor(timestamp / 60 / 60);
var minutes = Math.floor((timestamp - hours * 60 * 60) / 60);
var seconds = Math.floor(timestamp - hours * 60 * 60 - minutes * 60 );
var duration = hours + ':' + minutes + ':' + seconds;
 2
Author: milkovsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-05 17:54:24
 function getDateTimeFromTimestamp(unixTimeStamp) {
    var date = new Date(unixTimeStamp);
    return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
  }

var myTime = getDateTimeFromTimestamp(1435986900000);
console.log(myTime); // output 01/05/2000 11:00
 2
Author: Ashish Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-04 06:59:09
function getDateTime(unixTimeStamp) {

    var d = new Date(unixTimeStamp);
    var h = (d.getHours().toString().length == 1) ? ('0' + d.getHours()) : d.getHours();
    var m = (d.getMinutes().toString().length == 1) ? ('0' + d.getMinutes()) : d.getMinutes();
    var s = (d.getSeconds().toString().length == 1) ? ('0' + d.getSeconds()) : d.getSeconds();

    var time = h + '/' + m + '/' + s;

    return time;
}

var myTime = getDateTime(1435986900000);
console.log(myTime); // output 01/15/00
 1
Author: Bhaumik Mehta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-30 14:10:03