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

有什么建议吗?


当前回答

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

其他回答

 function ToLocalDate (inDate) {
    var date = new Date();
    date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
    return date;
}

我认为我有一个更简单的解决方案——将初始日期设置为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)

纪元时间是从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;
   }

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

您只是要求将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);