Convert UNIX timestamp to date time (javascript)

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

Timestamp:

1395660658

Code:

//timestamp conversion exports.getCurrentTimeFromStamp = function(timestamp) {     var d = new Date(timestamp);     timeStampCon = d.getDate() + '/' + (d.getMonth()) + '/' + d.getFullYear() + " " + d.getHours() + ':' + d.getMinutes();      return timeStampCon; };

This converts the time stamp properly in terms of time format, but the date is always:

17/0/1970

Why - cheers?

回答1:

You have to multiply by 1000 as JavaScript counts in milliseconds since epoch (which is 01/01/1970), not seconds :

var d = new Date(timestamp*1000);

Reference



回答2:

Because your time is in seconds. Javascript requires it to be in milliseconds since epoch. Multiply it by 1000 and it should be what you want.

//time in seconds var timeInSeconds = ~(new Date).getTime(); //invalid time console.log(new Date(timeInSeconds)); //valid time console.log(new Date(timeInSeconds*1000));


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!