I use Moment to handle time in my code.
Here is a question:
I want to judge two times, if now is the next day of last_take_time
If I write like this:
if not last_take_time? or (now.dayOfYear() - last_take_time.dayOfYear() is 1 )
do_something()
There is a problem when last_take_time is the end day of a year.
I am newbie with JavaScript and Moment, but I think there is a right way to judge this.
Thanks!
If you use dayOfWeek() then it is fairly easy to add an extra clause to test for the tricky case of Sunday / Monday:
if(last_take_time && (now.dayOfWeek() - last_take_time.dayOfWeek() == 1
|| (now.dayOfWeek() == 1 && last_take_time.dayOfWeek() == 7)))
do_something();
This is easier than dealing with the dayOfYear() because of having to deal with leap years.
Edit
Ah ok, I understand, you make a valid point - the answer above will return false positives when the days are more than a week apart. We can add a clause to account for this:
if(last_take_time && now.diff(last_take_time, 'days') < 3
&& (now.dayOfWeek() - last_take_time.dayOfWeek() == 1
|| (now.dayOfWeek() == 1 && last_take_time.dayOfWeek() == 7)))
do_something();
The additional clause uses the moment.js method diff(): link to docs to account for the highlighted issue.
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