Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With momentjs, how do I tell if 2 moments represent the same day (not, necessarily, the same time)?

I have 2 momentjs objects, moment1 and moment2:

enter image description here

Why is moment1.isSame(moment2, 'date') returning false??

My understanding is that checking moment1.isSame(moment2, 'day') returns whether they are the same day of the week (at least, that's what it looks like from the docs). So if both 'day' and 'date' don't work, what is the correct way to determine if the 2 dates represent the same day?

I could have sworn I've used moment1.isSame(moment2, 'date') in the past, but I must be remembering incorrectly...

like image 580
Troy Avatar asked Jan 25 '17 15:01

Troy


People also ask

How do I compare two dates in MomentJS?

We can use the isAfter method to check if one date is after another. Then we call isAfter on it with another date string and the unit to compare. There's also the isSameOrAfter method that takes the same arguments and lets us compare if one date is the same or after a given unit.

Is same in MomentJS?

This method will check if the moment is same as another moment. It returns true or false.

How do I get the current time in MomentJS?

To get the current date and time, just call javascript moment() with no parameters like so: var now = moment(); This is essentially the same as calling moment(new Date()) .

How do you check if a date is valid in moment?

isValid() is the method available on moment which tells if the date is valid or not. MomentJS also provides many parsing flags which can be used to check for date validation.


2 Answers

You can use both 'day' and 'date' to isSame.

As the docs says:

Check if a moment is the same as another moment.

When including a second parameter, it will match all units equal or larger. Passing in month will check month and year. Passing in day will check day, month, and year.

Like moment#isAfter and moment#isBefore, any of the units of time that are supported for moment#startOf are supported for moment#isSame.

In the docs of startOf:

Note: moment#startOf('date') was added as an alias for day in 2.13.0

Here a working example with the lastest version (2.17.1):

var moment1 = moment('01/23/17', 'MM/D/YYYY');
var moment2 = moment('01/23/17', 'MM/D/YYYY');
console.log( moment1.isSame(moment2, 'day') ); // true
console.log( moment1.isSame(moment2, 'date') ); // true
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
like image 162
VincenzoC Avatar answered Oct 08 '22 19:10

VincenzoC


Let's keep it simple.

moment(date1).format('L') === moment(date2).format('L')
like image 9
sonenko Avatar answered Oct 08 '22 19:10

sonenko