【问题标题】:setHour without change on Time ZonesetHour 时区不变
【发布时间】:2017-05-14 19:31:00
【问题描述】:

我在 node.js 上编写代码,我需要设置小时、分钟、秒到现在的日期而不更改时区。 (我从客户端获取时间,它按 UTC 时区以 hh:mm:ss 格式发送时间)

我设定时间的代码是:

  var now = new Date();

  console.log(now);
  now.setHours(format.h);
  now.setMinutes(format.m);
  now.setSeconds(format.s);

现在时间是:

2016-12-30T13:30:17.586Z

格式为:

13:29:29

当我设置秒时,结果是

2016-12-30T18:29:29.345Z

似乎时区正在改变;如何在不更改时区的情况下设置小时?

  • 更新

我安装了 momentjs,这是我的代码:

  var now = moment();
  console.log("before: " + now.format());
  now.add(format.h, 'hours');
  now.add(format.m, 'minutes');
  now.add(format.s, 'seconds');
  console.log("after: " + now.format());

这里是日志:

format time= 3:45:38
before: 2017-01-06T12:55:45+03:30
after: 2017-01-06T16:41:23+03:30

其实时间应该是2017-01-06T15:45:38+00:00

【问题讨论】:

标签: node.js timezone momentjs


【解决方案1】:

对于任何复杂的日期/时间操作,最好使用moment

moment().set('hour', 13);

这样可以省去很多麻烦。

见:http://momentjs.com/docs/

【讨论】:

    【解决方案2】:

    代替

    date.setHours()
    date.setMinutes()
    date.setSeconds()
    

    使用

    date.setUTCHours()
    date.setUTCMinutes()
    date.setUTCSeconds()
    

    一切都会按预期进行:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      相关资源
      最近更新 更多