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...
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.
This method will check if the moment is same as another moment. It returns true or false.
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()) .
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.
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 checkmonth
andyear
. Passing inday
will checkday
,month
, andyear
.Like
moment#isAfter
andmoment#isBefore
, any of the units of time that are supported formoment#startOf
are supported formoment#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>
Let's keep it simple.
moment(date1).format('L') === moment(date2).format('L')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With