【问题标题】:Moment.js to get UTC time as date object instead of stringMoment.js 将 UTC 时间作为日期对象而不是字符串
【发布时间】:2017-11-26 17:33:39
【问题描述】:

我想使用 moment.utc() 作为日期对象而不是纪元或字符串(moment.utc().format() 或使用 .toISOString())来获取 UTC 时间。 moment.utc().toDate() 返回我的当地时间。任何帮助将不胜感激。

【问题讨论】:

  • 使用 .toDate 方法:moment().toDate()。日期对象是 UTC。
  • 将该字符串转换为 Date 对象
  • “moment.utc().toDate() 返回我的本地时间” – 不,它返回一个 Date 对象。当 输出 需要将其转换为字符串值时,可能会在您的本地时间 显示,是的。
  • @RobG var utc_date = moment().toDate(); console.log('utc_date ' + utc_date); 输出 - 2017 年 6 月 23 日星期五 14:10:07 GMT+0530(印度标准时间)
  • @CBroe 我刚刚做了一个console.log。我错过了什么吗?

标签: javascript date momentjs utc


【解决方案1】:

您可以使用moment().toDate()。如果您将日期强制转换为字符串(例如,通过将其发送到控制台、警报等),内置(依赖于实现)toString 方法通常会使用主机时区设置来生成字符串,例如

var m = moment().toDate();  // Equivalent to new Date()

console.log(m + '') // coerce to string uses built-in toString
console.log(m.toISOString()) // ISO 8601 string offset +0000
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

【讨论】:

  • 显然他要的是 Date 对象,而不是字符串!
  • @JAN——见答案的第一条语句,它产生了一个 Date 对象。
猜你喜欢
  • 2012-03-15
  • 2019-09-07
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 2015-10-24
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多