我已经为此挣扎了一段时间。我正在尝试将epoch转换为日期对象。纪元以UTC格式发送给我。无论何时向new Date()传递一个epoch,它都假定它是本地epoch。我尝试创建一个UTC对象,然后使用setTime()将其调整为适当的epoch,但唯一有用的方法是toUTCString()和字符串对我没有帮助。如果我将这个字符串传递给一个新的日期,它应该注意到它是UTC,但它没有。

new Date( new Date().toUTCString() ).toLocaleString()

我的下一个尝试是试图获得本地当前epoch和UTC当前epoch之间的差异,但我也无法得到。

new Date( new Date().toUTCString() ).getTime() - new Date().getTime()

它只给了我非常小的差别,在1000以下,单位是毫秒。

有什么建议吗?


当前回答

纪元时间是从1970年1月1日开始的,单位为秒。date.getTime()返回1970年1月1日的毫秒数,因此..如果你有一个epoch时间戳,通过乘以1000将其转换为javascript时间戳。

   function epochToJsDate(ts){
        // ts = epoch timestamp
        // returns date obj
        return new Date(ts*1000);
   }

   function jsDateToEpoch(d){
        // d = javascript date obj
        // returns epoch timestamp
        return (d.getTime()-d.getMilliseconds())/1000;
   }

其他回答

我找到的最简单的解决方法是:

var timestamp = Date.now(), // returns milliseconds since epoch time
    normalisedTime = new Date(timestamp);

注意,在new Date(timestamp)语句的末尾没有* 1000,因为这个(至少对我来说!)似乎总是给出错误的日期,即给出的年份不是2019年而是51015年,所以请记住这一点。

纪元时间是从1970年1月1日开始的,单位为秒。date.getTime()返回1970年1月1日的毫秒数,因此..如果你有一个epoch时间戳,通过乘以1000将其转换为javascript时间戳。

   function epochToJsDate(ts){
        // ts = epoch timestamp
        // returns date obj
        return new Date(ts*1000);
   }

   function jsDateToEpoch(d){
        // d = javascript date obj
        // returns epoch timestamp
        return (d.getTime()-d.getMilliseconds())/1000;
   }

我认为我有一个更简单的解决方案——将初始日期设置为epoch并添加UTC单位。假设您有一个以秒为单位存储的UTC epoch var。1234567890怎么样?要将该日期转换为本地时区的正确日期:

var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);

d现在是一个日期(在我的时区)设置为2009年2月13日星期五18:31:30 GMT-0500 (EST)

将当前以[ms]为单位的epoch时间转换为24小时时间。您可能需要指定禁用12小时格式的选项。

$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"

2/7/2018, 19:35:24

或作为JS:

var date = new Date(Date.now()); 
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24

console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24

注意:这里使用的en-GB,只是一个使用24小时格式的地方的(随机)选择,它不是您的时区!

@Amjad,好主意,但更好的实现应该是:

Date.prototype.setUTCTime = function(UTCTimestamp) {
    var UTCDate = new Date(UTCTimestamp);
    this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate());
    this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds());
    return this.getTime();
}