【问题标题】:moment js 'from' giving weird result时刻 js 'from' 给出奇怪的结果
【发布时间】:2020-08-05 16:16:19
【问题描述】:

我从后端获取date,就像[2020, 8, 5, 13, 29, 43, 780000000](这是UTC 日期)。

我必须将此日期与当前 UTC 进行比较以获取相对时间。 在此示例中,当前 UTC 为:- 2020-08-05T15:59:52.514Z

预计的相对时间是 2 小时 30 分钟。我不确定为什么 Moment JS 的实际响应是 16 小时。

const timeInUTC = moment.utc(date)
const currentTimeInUTC = moment.utc(new Date().toISOString())
console.log(timeInUTC.from(currentTimeInUTC))

【问题讨论】:

  • 您能否提供更详细的示例,也许是date 的值。因为用_a检查每个日志,相对时间似乎是正确的
  • timeInUTC 的日期输入是一个数组 @hgb123
  • 您可以使用moment.utc() 来获取UTC 的当前时间。无需传递日期字符串,

标签: javascript momentjs moment-timezone


【解决方案1】:

问题出在格式上。输入到 moment 的日期是数组格式,而我正在以“UTC 格式”计算 UTC 的当前时间。

在确保两者具有相同的格式后解决了问题。

const dateInUTCFormat = new Date(
        Date.UTC(date.value[0], date.value[1] - 1, date.value[2], date.value[3], date.value[4], date.value[5])
    )

    const timeInUTC = moment(dateInUTCFormat)
    const currentTimeInUTC = moment.utc()
    console.log(timeInUTC.from(currentTimeInUTC)

)

【讨论】:

    猜你喜欢
    • 2013-08-20
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多