olefrank olefrank - 12 days ago 7
Javascript Question

How to compare dates with moment

I'm trying to compare dates from database (firebase) with NOW. I'm using moment.js and it's not working. I think it has something to do with the time zone (or UTC+01:00)...

Example.


  • date1: "2016-11-20T14:00:00"

  • NOW: "2016-11-20T14:49:20+01:00"



I get NOW with
moment()
and compare like this:

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.

Answer

Dates should always be saved in UTC. If you use string type the UTC date time value in ISO format.

So while saving convert from client time zone into UTC and while retrieving convert from UTC into client time zone.

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.

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

Change the NOW value to UTC before comparing.

moment.(date1).utc()

Alternatively you can change the database value from UTC to local.

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

Keep the NOW value as is before comparing.

Comments