【问题标题】:moment to date object timezone issue即时到日期对象时区问题
【发布时间】:2016-05-05 16:25:44
【问题描述】:

我有一个从 BST 中的 fullcalendar 生成的 moment.js 对象,如下所示:

console.log(momentSelected)
//Moment {_isAMomentObject: true, _isUTC: true, _offset: 0, _locale: f, _d: Tue May 03 2016 01:00:00 GMT+0100 (BST)…}

我不想要一个 BST 时间,而是一个如下所示的 UTC 时间:

console.log(momentSelected.format('YYYY-MM-DD HH:mm Z'));
//2016-05-03 00:00 +00:00 

现在我需要将其转换为 Date 对象:

$scope.date = new Date(momentSelected.format('YYYY-MM-DD HH:mm Z'));
console.log($scope.date);
//Wed May 04 2016 01:00:00 GMT+0100 (BST) 

最后输出错误...我要Wed May 04 2016 00:00:00+00:00 (UTC)

【问题讨论】:

  • 但它显示_isUTC: true, _offset: 0 已经是UTC。也许你需要使用Date.prototype.toUTCString()
  • 是的,我同意,为什么它会在 BST 中创建一个 Date 对象...
  • @Matt 的回答解释了这一点(如果您的本地时区是英国(在 GMT 和 BST 之间交替进行夏令时),那么就不可能在生成的字符串中获得 (UTC) 时间通过console.log($scope.date);,不管你如何创建那个日期)
  • 另外,console.log 触发日期对象的 .toString() 原型,用于在本地时区打印日期 (adripofjavascript.com/blog/drips/…)

标签: angularjs fullcalendar momentjs


【解决方案1】:

您可以在 moment 对象上使用 toDate 函数创建 Date 对象。

$scope.date = momentSelected.toDate();

但是,您必须认识到Date 对象的本质是它始终在内部代表UTC,并且它的toString 函数将始终反映运行代码的本地时区。

如果您的本地时区是英国(在 GMT 和 BST 之间交替进行夏令时),那么无论您如何创建该日期,都无法在 console.log($scope.date); 生成的字符串中获得 (UTC) 时间。

这就是为什么最好使用 moment 的 format 函数并直接显示该字符串。 moment 可以反映 UTC、本地时间和其他时区。 Date 对象不能。

此外,您不应注意moment 对象的下划线前缀内部字段。请改用公共 API。请参阅moment user guide

【讨论】:

  • 我终于明白了!如何访问内部存储的 UTC 时间。基本上我拥有的每个日期都在使用时刻并且是 UTC,但是对于这件事我必须使用我需要一个日期对象。所以 $scope.date 是现在我需要转换的日期对象回到时刻,但时刻已经关闭了一小时。所以我需要与 toDate() 方法相反的方法。
  • 我认为您正在寻找 .utc().local() 函数。然后,您可以使用format 来生成您喜欢的字符串。确实,在使用 moment.js 时,您应该避免使用 Date 对象,除非您确实需要它,例如与需要它的其他组件交互。
  • 告诉我...创建该对象的人应该被串起来!
  • 哦,如果你想进入历史,你将不得不求助于委员会而不是一个人。 ;) 我可以就这个主题发表论文...
猜你喜欢
  • 2013-10-29
  • 2019-06-05
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
  • 2018-03-21
  • 2016-12-14
  • 2015-05-24
  • 1970-01-01
相关资源
最近更新 更多