Sometimes, we want to test if a date is today, yesterday, within a week or two weeks ago with moment.js
In this article, we’ll look at how to test if a date is today, yesterday, within a week or two weeks ago with moment.js.
Test if a Date is Today, Yesterday, within a Week or Two Weeks Ago with Moment.js
To test if a date is today, yesterday, within a week or two weeks ago with moment.js, we can use the isSame
and isAfter
methods to compare dates.
For instance, we can write:
const REFERENCE = moment("2021-06-05");
const TODAY = REFERENCE.clone().startOf('day');
const YESTERDAY = REFERENCE.clone().subtract(1, 'days').startOf('day');
const A_WEEK_OLD = REFERENCE.clone().subtract(7, 'days').startOf('day');
const isToday = (momentDate) => {
return momentDate.isSame(TODAY, 'd');
}
const isYesterday = (momentDate) => {
return momentDate.isSame(YESTERDAY, 'd');
}
const isWithinAWeek = (momentDate) => {
return momentDate.isAfter(A_WEEK_OLD);
}
const isTwoWeeksOrMore = (momentDate) => {
return !isWithinAWeek(momentDate);
}
console.log(isToday(moment("2021-06-05")));
console.log(isYesterday(moment("2021-06-04")));
console.log(isWithinAWeek(moment("2021-06-03")));
console.log(isWithinAWeek(moment("2021-05-29")));
console.log(isTwoWeeksOrMore(moment("2021-05-30")));
console.log(isTwoWeeksOrMore(moment("2021-05-29")));
We have the REFERENCE
date that we want to do various checks with.
TODAY
is a copy of RERFERENCE
, which is created by clone
and then we set it to the start of the date with the startOf
method.
YESTERDAY
is a clone of REFERENCE
subtract one day with subtract
.
A_WEEK_OLD
is a clone of REFERENCE
subtract 7 days with subtract
.
They’re also set to the start of the date with startOf
.
Then we create the isToday
function to call the isSame
method on momentDate
to check if the date is the same as TODAY
.
We compare by date since we passed in 'd'
as the 2nd argument.
Similarly, we use similar code to create isYesterday
but with YESTERDAY
instead of TODAY
.
To create the isWithinWeek
function, we use the isAfter
function to check if the momentDate
is after the start of a given week, which we stored in A_WEEK_OLD
,
And we check is 2 weeks or more before a given momentDate
with the isWithinAWeek
function.
Therefore, from the console log, we should get:
true
true
true
false
false
true
as a result.
Conclusion
To test if a date is today, yesterday, within a week or two weeks ago with moment.js, we can use the isSame
and isAfter
methods to compare dates.