【问题标题】:Why is an hour being added to the time when adding a timezone offset?为什么在添加时区偏移时要在时间上增加一个小时?
【发布时间】:2015-10-29 09:56:11
【问题描述】:

我正在使用 Moment 和 Moment 时区。

我有一个 unix 时间戳,然后我想只添加时区偏移量,但偏移量也被添加到时间中 - 我不想要这个:

var testDateTimeUnix = 1438352400; 
// Fri, 31 Jul 2015 14:20:00 
var testDateTimeUnixFormatted = moment(testDateTimeUnix, 'X').utc().format() 
// "2015-07-31T14:20:00+00:00"
var testDateTimeWithTimezoneOffset = moment(testDateTimeUnixFormatted).utc().tz('Europe/Bucharest').format(); 
// “2015-07-31T17:20:00+03:00"

我想要的格式化日期是:

"2015-07-31T14:20:00+03:00"

任何帮助将不胜感激。

【问题讨论】:

标签: momentjs


【解决方案1】:

我不知道你为什么要这样做...当显示 17:20:00+03:00 时,这意味着 3 小时的偏移量包含在时间中。这意味着我知道在时刻或时刻时区中没有任何方法可以提供帮助,因为它们总是将偏移量应用于时刻。

有一种 hacky 方式,非常肮脏,我不建议将它用于生产代码,因为它依赖于内部结构并且很可能会破坏库中的其他内容(您已收到适当警告:))

var moment = require( 'moment-timezone' ),

// your timestamp
tx = 1438352400;
// expressed as a moment in UTC
txu = moment( tx, 'X').utc();
// now get the UTC offset for Bucharest (in minutes) 
txo = moment().tz('Europe/Bucharest').utcOffset();

// This is the dirty part and we hack the moment's internal structure. Bad.
// Set the offset to Bucharest's
txu._offset = txo; 

// and display
console.log( txu.format() );
// 2015-07-31T14:20:00+03:00

```

所以它是可行的,但我不知道最终值代表什么时间。 Moment抵消时间是有原因的。

【讨论】:

  • 感谢 tgo 的回复 - 这与我实现的非常相似。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
  • 2017-11-10
  • 2016-04-28
  • 2018-02-20
  • 2020-05-23
  • 2020-01-29
相关资源
最近更新 更多