With momentjs, how do I tell if 2 moments represen

2019-06-15 16:25发布

问题:

I have 2 momentjs objects, moment1 and moment2:

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...

回答1:

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>