【问题标题】:javascript setUTCMilliseconds is wrong? Otherwise, I'm wrongjavascript setUTCMilliseconds 错了吗?否则我错了
【发布时间】:2012-05-09 00:53:54
【问题描述】:

我是否错误地实现了 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) 

【问题讨论】:

  • 您传递的值不是一个纪元,而是一个纪元的时间。
  • 是的,我明白这个数字的含义。我在这里像epochtime一样使用它

标签: javascript date utc milliseconds


【解决方案1】:

来自一个类似的问题:

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

Convert UTC Epoch to local date with javascript

【讨论】:

  • 是的,我试过了,它只是显示了 1970 年的纪元日期。
  • 啊,好吧,确实需要 0,但没有注意到它的秒数,而不是毫秒。
  • 由于时间是以秒为单位的,你可以这样做:d.setUTCSeconds(seconds, 0)
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多