简体   繁体   English

如何将日期与时刻进行比较

[英]How to compare dates with moment

I'm trying to compare dates from database (firebase) with NOW. 我正在尝试将数据库(firebase)中的日期与NOW进行比较。 I'm using moment.js and it's not working. 我正在使用moment.js,但无法正常工作。 I think it has something to do with the time zone (or UTC+01:00)... 我认为这与时区(或UTC + 01:00)有关...

Example. 例。

  • date1: "2016-11-20T14:00:00" date1:​​“ 2016-11-20T14:00:00”
  • NOW: "2016-11-20T14:49:20+01:00" 现在:“ 2016-11-20T14:49:20 + 01:00”

I get NOW with moment() and compare like this: 我现在获得moment()并进行如下比较:

var date1 = moment("2016-11-20T14:00:00");
moment(date1).isSameOrAfter( moment() ) // returns true

The comparison is precisely one hour off... How can I fix this? 比较恰好一个小时。。。如何解决这个问题? AND: is there any best practice in storing and comparing dates across time zones. AND:在跨时区存储和比较日期方面是否有最佳实践。

Dates should always be saved in UTC. 日期应始终保存在UTC中。 If you use string type the UTC date time value in ISO format. 如果使用字符串,请以ISO格式键入UTC日期时间值。

So while saving convert from client time zone into UTC and while retrieving convert from UTC into client time zone. 因此,在保存从客户端时区到UTC的转换以及从UTC到客户端时区的转换的同时。

Comparison should be done between two dates in the same time zone. 应该在同一时区中的两个日期之间进行比较。

If the database value is in UTC and then you have to parse as .utc() while creating a moment object. 如果数据库值使用UTC,则在创建矩对象时必须将其解析为.utc()。

moment.utc("2016-11-20T14:00:00");

Change the NOW value to UTC before comparing. 比较之前将NOW值更改为UTC。

moment.(date1).utc()

Alternatively you can change the database value from UTC to local. 或者,您可以将数据库值从UTC更改为local。

 moment.utc("2016-11-20T14:00:00").local()

Keep the NOW value as is before comparing. 比较之前,请保持NOW值不变。

You cannot compare the date you stored in Firebase with now() as it lacks the information about your timezone. 您无法将存储在Firebase中的日期与now()进行比较,因为它缺少有关时区的信息。

You can store dates using Firebase.ServerValue.TIMESTAMP 您可以使用Firebase.ServerValue.TIMESTAMP存储日期

For Example: 例如:

date1: Firebase.ServerValue.TIMESTAMP

This will save your time in Unix Milliseconds (time since the Unix epoch, in milliseconds) by the Firebase Database servers. 这将通过Firebase数据库服务器节省您以Unix毫秒为单位的时间(自Unix纪元以来的时间,以毫秒为单位)。

Then you can compare with new Date().getTime() this will give your device time in Unix Milliseconds. 然后,您可以与new Date().getTime()比较,这将为您的设备提供Unix毫秒的时间。

For Example: 例如:

if(new Date().getTime() >= date1) {
    //do something
}

Hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM