【问题标题】:Convert UTC date to milliseconds JavaScript将 UTC 日期转换为毫秒 JavaScript
【发布时间】:2019-12-05 05:57:23
【问题描述】:

我需要在我的 React Native 应用程序中比较两个日期:当前日期与服务器一个 UTC 格式的日期。这里最好的方法是什么?

我想过将两个日期转换为毫秒,然后再转换。

例子:

2019-06-20T14:26:58Z - 毫秒

current date - 毫秒

那么,这里最好的方法是什么?

它是 React Native,所以它应该可以在没有连接 chrome 调试器的情况下工作。

【问题讨论】:

标签: javascript reactjs react-native time momentjs


【解决方案1】:

momentjs 查询 API 有几种比较日期的有用方法。这是isSame 方法的示例。还有其他的,包括isSameOrBeforeisAfterisSameOrAfter 等等。

// convert current date to UTC
const currentDateUtc = moment(currentDate).utc();

// check if current date is the same as the server date
currentDateUtc.isSame(moment(serverDate).utc())

在他们的文档中了解更多关于 moment's query API 的信息。

【讨论】:

    【解决方案2】:

    您可以使用Date.getTime()

    const serverTime = new Date('2019-06-20T14:26:58Z')
    const currentTime = new Date()
    
    console.log({
      serverTime: {
        milliseconds: serverTime.getTime(),
        toString: serverTime.toString()
      }
    })
    
    console.log({
      currentTime: {
        milliseconds: currentTime.getTime(),
        toString: currentTime.toString()
      }
    })
    
    console.log(serverTime.getTime() < currentTime.getTime())

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 2019-12-24
      相关资源
      最近更新 更多