我已经为此挣扎了一段时间。我正在尝试将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以下,单位是毫秒。

有什么建议吗?


当前回答

您只是要求将UTC字符串转换为“本地”字符串吗?你可以这样做:

var utc_string = '2011-09-05 20:05:15';
var local_string = (function(dtstr) {
    var t0 = new Date(dtstr);
    var t1 = Date.parse(t0.toUTCString().replace('GMT', ''));
    var t2 = (2 * t0) - t1;
    return new Date(t2).toString();
})(utc_string);

其他回答

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

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

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

纪元时间(即Unix纪元时间)几乎总是自1970年1月1日00:00:00 (UTC时间)以来已经过期的秒数,而不是这里的一些答案所暗示的毫秒数。

https://en.wikipedia.org/wiki/Unix_time

因此,如果给您一个Unix Epoch时间值,它可能以秒为单位,看起来像1547035195。如果你想让这个值在JavaScript中成为人类可读的,你需要将值转换为毫秒,并将该值传递到Date(value)构造函数中,例如:

const unixEpochTimeMS = 1547035195 * 1000;
const d = new Date(unixEpochTimeMS);
// Careful, the string output here can vary by implementation...
const strDate = d.toLocaleString();

您不需要在接受的答案中执行d.setUTCMilliseconds(0)步骤,因为JavaScript Date(value)构造函数采用以毫秒为单位的UTC值(而不是本地时间)。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax

还要注意,你应该避免使用Date(…)构造函数,它接受一个字符串日期时间表示,这是不建议的(参见上面的链接)。

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

纪元时间是从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_time可用,

// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB');  // 24 hour format