Incrementing a date in JavaScript
Getting straight to it, here's how you boost a Date
by one day in JavaScript:
This snippet takes care of month-end and leap years, automatically adjusting the date. Just replace 1
with any other number of days you wish to increment by.
Time Zone & Daylight Saving Time: An Unholy Union
Keep Calm and Use UTC
To dodge any pesky time zone related inconsistencies, choose to work with UTC dates:
With this, you can say goodbye to woes of local time adjustments and daylight saving shifts.
DST: Not a Time Travel Movie
While juggling with local times, remain vigilant of the notorious Daylight Saving Time changes:
This makes sure that hours remain constant even if DST meddles with the time.
What Could Go Wrong?
Superheroes: Month & Year Rollover
One league where JavaScript's Date
shines is in handling rollovers:
Leap Years: Not so Leap
Worried about leap years? JavaScript's got you:
Hello MomentJS
For a more uplifted API you could consider libraries like MomentJS:
But remember, cloning instead of mutating is the golden rule:
Be aware, though, MomentJS carries its costs and for simpler tasks, native JavaScript could be lighter and speedier.
Code Shortcuts
Milliseconds: The Game Changer
Direct millisecond arithmetic to the rescue:
One-liners: Brevity at its Best
Conciseness, here we come:
This one-liner has its charms, but turns a blind eye to time zones and DST changes.
Make it Stick: Saving the Incremented Date
When incrementing within loops or complex functions, always save the results:
Was this article helpful?