How can I convert a date in Epoch to "Y-m-d H:i:s" in Javascript?

James Cazzetta picture James Cazzetta · May 10, 2012 · Viewed 42.9k times · Source

How can I convert following date in epoch:

1293683278

to following readable date:

2010-06-23 09:57:58

using Javascript?

Thanks!

Answer

deadrunk picture deadrunk · May 10, 2012

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();

console.log(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})/)

console.log(iso[1] + ' ' + iso[2]);