将日期时间与当前日期时间进行比较

时间:2020-01-02 07:53:52

标签: javascript

从服务器上,我得到一个类似“ Thu,02-Jan-2020 08:32:18 GMT”这样的日期时间,我想将其与当前GMT日期时间进行比较。我将如何在javascript中做到这一点。

2 个答案:

答案 0 :(得分:3)

const serverDate = new Date('Thu, 02-Jan-2020 08:32:18 GMT');
const clientDate = new Date();
const clientOffset = clientDate.getTimezoneOffset() * 60 * 1000; // get milliseconds from minutes

if (serverDate.getTime() > clientDate.getTime() + clientOffset) {
  console.log('serverDate is later than clientDate');
} else {
  console.log('serverDate is earlier than clientDate');
}

在这里,我们正在使用内置的Date对象。此示例中的getTime()方法用于获取自1970年1月1日以来经过的毫秒数。这样一来,我们最终仅比较了两个数字。

如果您在客户端设备上设置的时区与服务器上的格林尼治标准时间+0不同,则getTimezoneOffset()会有所帮助。它返回我们需要添加到getTime()结果中的分钟数,以便客户端时间戳也将位于GMT + 0时区。

答案 1 :(得分:0)

我建议使用moment.js。使用它就像x.isSameAs(y),x.isBefore(y)x.isAfter(y)一样简单