Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing today's date with another date in moment is returning the wrong date, why?

I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.

code:

var releaseDate = moment("2012-09-25"); var now = moment(); //Today is 2012-09-25, same as releaseDate   console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD")); console.log("NOW: " + now.format("YYYY-MM-DD")); console.log("DIFF: " + now.diff(releaseDate, 'days')); 

console:

RELEASE: 2012-09-25 NOW: 2012-09-25 DIFF: 1  

Ideas?

like image 435
manafire Avatar asked Sep 26 '12 02:09

manafire


People also ask

How do you compare two dates for a moment?

To compare two dates in moment js, The momentjs provide isBefore() , isSame() , isAfter() , isSameOrBefore() , isSameOrAfter() , and isBetween() to compare dates as you want.

How do you calculate days difference between two dates using moments?

If you are using a date and time field and would like to output the difference between the two dates in days, hours and minutes, use the following template: var m1 = moment('{admission}', 'DD-MM-YYYY HH:mm'); var m2 = moment('{discharge}', 'DD-MM-YYYY HH:mm'); var m3 = m2. diff(m1,'minutes'); var m4 = m2.


2 Answers

Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:

var now = moment(); 

creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.

The statement:

var releaseDate = moment("2012-09-25"); 

creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.

moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:

 now.diff(releaseDate, 'days', true)  ------------------------------^ 

So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.

If you want to compare just dates, then use:

var now = moment().startOf('day');  

which will set the time to 00:00:00 in the local time zone.

like image 131
RobG Avatar answered Sep 27 '22 18:09

RobG


RobG's answer is correct for the question, so this answer is just for those searching how to compare dates in momentjs.

I attempted to use startOf('day') like mentioned above:

var compare = moment(dateA).startOf('day') === moment(dateB).startOf('day'); 

This did not work for me.

I had to use isSame:

var compare = moment(dateA).isSame(dateB, 'day'); 
like image 24
zacharydl Avatar answered Sep 27 '22 17:09

zacharydl