How can I convert a date in Epoch to “Y-m-d H:i:s”

2019-04-04 02:24发布

问题:

How can I convert following date in epoch:

1293683278

to following readable date:

2010-06-23 09:57:58

using Javascript?

Thanks!

回答1:

var timestamp = 1293683278;
var date = new Date(timestamp*1000);

var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();

alert(year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds);

See js Date docs for further details

Another way:

var timestamp = 1293683278;
var date = new Date(timestamp*1000);
var iso = date.toISOString().match(/(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})/)
alert(iso[1] + ' ' + iso[2]);


回答2:

You can use moment.js for this.

moment.unix(1293683278).format('YYYY-MM-DD HH:mm:ss');


回答3:

Code:

var timestamp = 1293683278;
var d = new Date(timestamp*1000);
alert(
    d.getFullYear() + "-" + 
    ("00" + (d.getMonth() + 1)).slice(-2) + "-" + 
    ("00" + d.getDate()).slice(-2) + " " + 
    ("00" + d.getHours()).slice(-2) + ":" + 
    ("00" + d.getMinutes()).slice(-2) + ":" + 
    ("00" + d.getSeconds()).slice(-2)
);

Format: YYYY-MM-DD HH:II:SS

Result: 2010-12-30 07:57:58

Demo: https://jsfiddle.net/NabiKAZ/9ycovfxt/

Note: For current time, just use: var d = new Date(); instead.



回答4:

/* Get timestamp */
var timestamp = 1293683278;
document.querySelector("#timestamp").innerHTML = "Timestamp: " + timestamp;

/* Get milisecond from timestamp */
var milisecond = 1293683278 * 1000;    
document.querySelector("#milisecond").innerHTML = "Milisecond: " + milisecond;
  
/* Separate milisecond */
var datetime = new Date(milisecond);

var year    = datetime.getFullYear();
var month   = datetime.getMonth() + 1; // (0-11)
var date    = datetime.getDate();
var hour    = datetime.getHours();
var minute  = datetime.getMinutes();
var second  = datetime.getSeconds();

document.querySelector("#datetime").innerHTML = "Datetime: " + 
  year + "-" + addZero(month) + "-" + addZero(date) + " " + 
  addZero(hour) + ":" + addZero(minute) + ":" + addZero(second);      

// Add 0 if argument < 10
function addZero(i) {
  if (i < 10) {
    i = "0" + i
  };  
  return i;
}
<p id="timestamp"><p>
<p id="milisecond"><p>
<p id="datetime"><p>