JavaScript setUTCMilliseconds是错误的?否则,我错了

javascript setUTCMilliseconds is wrong? Otherwise, I'm wrong

本文关键字:否则 我错了 setUTCMilliseconds 错误 JavaScript      更新时间:2023-09-26

我是否错误地实现了setUTCMilliseconds?我输入的任何值的日期都不正确。这里只是一个错误值的示例。我所有的测试数据在JS中解析为5月24日(从现在开始的未来),但是在C#或使用快速在线转换工具中,我的UTS MS是正确的。

有什么想法吗?

function parseDate(epoch) {   
    var d = new Date();
    //tried this too, but it shows me the actual epoch 1970 date instead
    //var d = new Date(0);
    //EDIT: this should be seconds in combination with Date(0)
    d.setUTCMilliseconds(parseInt(epoch)); 
    return d.toString();
}
 // 1336423503 -> Should be Mon May 07 2012 13:45:03 GMT-7
 // javascript says
 Thu May 24 2012 05:03:21 GMT-0700 (Pacific Daylight Time) 

来自一个类似的问题:

var utcMilliseconds = 1234567890000;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCMilliseconds(utcMilliseconds);

请参阅使用 javascript 将 UTC 纪元转换为本地日期。

将 UTC 时间(以秒为单位)转换为本地日期对象:

function makeUTC(secs) {
  return new Date(Date.UTC(1970,0,1,0,0, secs, 0));
}

请注意,纪元为 1970-01-01T00:00:00.0Z

只需使用以毫秒作为数字的 Date() 构造函数:

> new Date(1336423503 * 1000)
2012-05-07T20:45:03.000

无需创建 Date 对象并在之后设置 UTCMilliseconds。