Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js Check a date is today

How do I check a date is actually today (the same date) rather than the difference between hours in a day?

I have three timestamps as examples, one is today (22/07/14) and the other two are yesterday (21/07/14)

1406019110000 // today 1405951867000 // yesterday 1405951851000 // yesterday 

I have tried this but all return false:

timestamp = moment.tz(timestamp, tz.name());     var today = moment('DD/MM/YYYY').isAfter(timestamp, 'DD/MM/YYYY'); console.log(today); 
like image 241
Asa Carter Avatar asked Jul 22 '14 09:07

Asa Carter


People also ask

How can I compare current date and moment in different date?

We can use the isAfter method to check if one date is after another. We create a moment object with a date string. Then we call isAfter on it with another date string and the unit to compare.

How can I get tomorrow date in moment?

to create the tomorrow variable that's set to a moment object with today's date. Then we call add with -1 and 'days' to subtract one day to today. And then we call format with 'YYYY-MM-DD' to format the date to YYYY-MM-DD format.


2 Answers

You can use isSame(), limiting the granularity to a day:

var today = moment(1406019110000); var yesterday = moment(1405951867000);  if (today.isSame(yesterday, 'd')) {     // They are on the same day } else {     // They are not on the same day } 
like image 91
Vasyl Demin Avatar answered Sep 26 '22 04:09

Vasyl Demin


You can use the startOf and isSame methods together to achieve your goal here.

Running startOf('day') on a moment object will set that moment to - you guessed it - the start of the day it occurs on. If you convert each of your timestamps using this method you can easily compare them to one another using isSame().

For example:

var today = moment(1406019110000); var yesterday = moment(1405951867000);   if (today.startOf('day').isSame(yesterday.startOf('day'))) {     // They are on the same day } else {     // They are not on the same day } 
like image 28
Cameron Avatar answered Sep 24 '22 04:09

Cameron