Working with dates in 2020 are still a mess. Presumably, they’ll also be a mess to work within 2021, 2022 and for a good while after that. Many (myself included) reach for a date library to fill the gaps.
For years Moment.js reigned supreme and for good reason, it can do everything with dates, including working with different time zones. Unfortunately, Moment can also result in bundle bloat.
And then came along date-fns. It could do almost everything Moment did and was good enough for 95% of all date and time related use cases. However, depending on the task, you can still use native vanilla Javascript to work with dates.
One such task I did recently was needing to calculate a day from today, my scenario was six months, but the solution I am going to show you can be changed to be any value and work for days and so on.
const SIX_MONTHS_AGO = new Date(); SIX_MONTHS_AGO.setMonth(SIX_MONTHS_AGO.getMonth() - 6);
We create a new date object, then we set the month to that of our month value minus 6 (where 6 is the number of months we want to go back). You can also change this so you can go 6 months into the future by changing the minus to a plus.
Finally, if you want to do date comparison and take a date and determine if it is older than six months, we can do something like this.
export const compareDates = (a: string | Date, b: string | Date): boolean => { const dateA = new Date(a).getTime(); const dateB = new Date(b).getTime(); return dateB > dateA; }
This will determine if the second value supplied to our function is greater than the first value supplied. The first value is the base and the second value is the comparative value.
If you were to call compareDates
with SIX_MONTHS_AGO
as the first argument and new Date()
as the second, we know the result would be true as today’s date is definitely older than six months ago.
compareDates(SIX_MONTHS_AGO, new Date())
No additional libraries required. I agree that the syntax is a little dry in comparison to the nicer API’s of Moment and date-fns, but it’s still a lighter and viable option.