One of the more infamous sides of JavaScript has been its date and time constructs. After years of having to use Datejs/Moment.js for many date-handling tasks, I have found more and more that the native Date constructor is almost always good enough, saving many precious bytes to download.
In JavaScript, you can add X days to a Date object by utilizing the built-in overflow capabilities. If you add 100 days to a Date object it will automatically increment the month or even year to produce a valid date offset by those 100 days.
const date = new Date(‘2022-02-02’);
console.log(date);
// Outputs: 2022-02-02T00:00:00.000Z
date.setDate(date.getDate() + 100);
console.log(date);
// Outputs: 2022-05-12T23:00:00.000Z
Cool!
The same technique also works well with all other date properties from milliseconds to months. 🙂
You can also use it for stepping backward in time:
const date = new Date(‘2022-02-02’);
console.log(date);
// Outputs: 2022-02-02T00:00:00.000Z
date.setMonth(date.getMonth() + 6);
console.log(date);
// Outputs: 2022-08-01T23:00:00.000Z
NOTE: There is one caveat here, getMonth/setMonth uses 0 indexing for the month numbers (0-11), so January is 0, December 11, and so on.
What is next up for date and time?
There is a new Temporal API in the working, but for now, none of the browsers has support for this yet: https://caniuse.com/?search=temporal
Fingers crossed that the specification can soon be finalized so that polyfills that implement the new standard can be created until the API becomes available in modern browsers.
Gone is the fear of losing track of time!