I need to display a formatted date from a timestamp provided by Google Analytics Standard solution like
var date = new Date(timestamp * 1000);
var formatted = date.toString();
produces wrong value Jan 01 1970
. That's because of timestamp format.
In PHP I can specify the timestamp format:
\DateTime::createFromFormat('Ymd', $timestamp);
How to do this in JS?
Since the dates you are receiving are formatted as YYYYMMDD
, not as a Unix
timestamp, you can parse it by
extracting the year, month and date using String.prototype.slice
.
var timestamp = '20170306',
year = parseInt(timestamp.slice(0, 4), 10),
month = parseInt(timestamp.slice(5, 6), 10),
day = parseInt(timestamp.slice(7, 8), 10);
// - 1 because the Date constructor expects a 0-based month
date = new Date(Date.UTC(year, month - 1, day)),
gmt = date.toGMTString(),
local = date.toString();
console.log('GMT:', gmt); // Mon, 06 Mar 2017 00:00:00 GMT
console.log('Local:', local);
This assumes that the dates you are using are in UTC (which they likely are). Date.UTC
creates a timestamp (in milliseconds since Unix epoch) and then feeds it into new Date()
which uses it to create a Date
object representing that time. .toGMTString()
outputs the date formatted for the GMT timezone. To output it formatted in local time, use .toString()
instead.