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);
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.
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.
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 }
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 }
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