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

2019-04-04 02:19发布

How can I convert following date in epoch:

1293683278

to following readable date:

2010-06-23 09:57:58

using Javascript?

Thanks!

4条回答
来,给爷笑一个
2楼-- · 2019-04-04 02:23

You can use moment.js for this.

moment.unix(1293683278).format('YYYY-MM-DD HH:mm:ss');
查看更多
手持菜刀,她持情操
3楼-- · 2019-04-04 02:23

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楼-- · 2019-04-04 02:34
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]);
查看更多
Ridiculous、
5楼-- · 2019-04-04 02:41

/* 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>

查看更多
登录 后发表回答