[javascript] Timestamp to human readable format

Well I have a strange problem while convert from unix timestamp to human representation using javascript

Here is timestamp

1301090400

This is my javascript

var date = new Date(timestamp * 1000);
var year    = date.getFullYear();
var month   = date.getMonth();
var day     = date.getDay();
var hour    = date.getHours();
var minute  = date.getMinutes();
var seconds = date.getSeconds();  

I expected results to be 2011 2, 25 22 00 00. But it is 2011, 2, 6, 0, 0, 0 What I miss ?

This question is related to javascript timestamp

The answer is


Hours, minutes and seconds depend on the time zone of your operating system. In GMT (UST) it's 22:00:00 but in different timezones it can be anything. So add the timezone offset to the time to create the GMT date:

var d = new Date();
date = new Date(timestamp*1000 + d.getTimezoneOffset() * 60000)

use Date.prototype.toLocaleTimeString() as documented here

please note the locale example en-US in the url.


here is kooilnc's answer w/ padded 0's

function getFormattedDate() {
    var date = new Date();

    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var min = date.getMinutes();
    var sec = date.getSeconds();

    month = (month < 10 ? "0" : "") + month;
    day = (day < 10 ? "0" : "") + day;
    hour = (hour < 10 ? "0" : "") + hour;
    min = (min < 10 ? "0" : "") + min;
    sec = (sec < 10 ? "0" : "") + sec;

    var str = date.getFullYear() + "-" + month + "-" + day + "_" +  hour + ":" + min + ":" + sec;

    /*alert(str);*/

    return str;
}

var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();

Where unixtime is the time returned by your sql db. Here is a fiddle if it helps.

For example, using it for the current time:

_x000D_
_x000D_
document.write( new Date().toUTCString() );
_x000D_
_x000D_
_x000D_