How to add hours to a Date object?
Add hours to a JavaScript Date
object using its setHours
method, coupled with getHours
. Like this:
This line of code modifies date
by 2 hours ahead.
Extending Date prototype for frequent use
When you find yourself often adding hours, extending the Date.prototype
can be a time-saving solution. Keep your code DRY (Don't Repeat Yourself) with this method:
Here we’ve created a custom method, addHours
, making use of the fact that time in JavaScript is measured in milliseconds.
Creating non-mutating function
Immutability is a crucial concept in several programming contexts. Here's how you can add hours to a Date
object without modifying the original data:
This approach ensures the integrity of your data by returning a new Date instance.
Overflow management using setHours
Sometimes when you add hours to a date, it can cause the date to overflow to the next day. JavaScript's setHours
method has got your back:
It adjusts the date appropriately in case of overflow. The MDN documentation provides further insights on this.
Practical tips and hazards to avoid
Discouraging string parsing
When adding hours to a date, it's much safer to use Date object methods rather than relying on string parsing:
Mindful of edge cases
Keep in mind edge cases such as daylight saving time changes — they can occasionally disrupt your hour calculations. An essential point if your application caters to an international audience.
JavaScript's inadequate Date/Time API
Sometimes, the best way to address JavaScript's poor Date/Time API is to make a note of it for your co-developers. Being explicit in code comments or documentation about your custom Date extensions can save future headaches.
Was this article helpful?