Explain Codes LogoExplain Codes Logo

How to add hours to a Date object?

javascript
date-prototype
custom-methods
immutability
Nikita BarsukovbyNikita Barsukov·Sep 2, 2024
TLDR

Add hours to a JavaScript Date object using its setHours method, coupled with getHours. Like this:

let date = new Date(); // Create a new date object date.setHours(date.getHours() + 2); // Travel forward in time by 2 hours

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:

Date.prototype.addHours = function(h) { this.setTime(this.getTime() + (h*60*60*1000)); // All aboard the time machine! 🚀 return this; }; let date = new Date(); console.log(date.addHours(3)); // Adds 3 hours to your time travel journey

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:

function addHoursTo(date, hours) { return new Date(date.getTime() + hours * 3600000); // Create a new date, as fresh as a morning sunrise 🌅 } let date = new Date(); let newDate = addHoursTo(date, 3); // Returns a new Date object, 3 hours ahead

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:

date.setHours(date.getHours() + 25); // Time travel to tomorrow! ⏰

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:

// Risky method. Butterfingers might make mistakes. 😰 let newDate = new Date('2023-01-01T00:00:00'); newDate.setHours(newDate.getHours() + 3); // The safe house. No sweat. 😇 let newDate = new Date(2023, 0, 1); newDate.setHours(newDate.getHours() + 3);

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.