Add time to string data/time - JavaScript?

In JavaScript, you can add time to a date/time string using the Date object's built-in methods. This is useful for calculating future times or adjusting existing timestamps.

Basic Approach

First, create a Date object from your string, then use methods like setHours(), setMinutes(), or setSeconds() combined with their getter counterparts to add time.

var dateValue = new Date("2021-01-12 10:10:20");
dateValue.setHours(dateValue.getHours() + 2);  // Add 2 hours

Example: Adding Hours to Date String

var dateValue = new Date("2021-01-12 10:10:20");
console.log("Original date: " + dateValue.toString());

// Add 2 hours
dateValue.setHours(dateValue.getHours() + 2);
console.log("After adding 2 hours: " + dateValue.toString());
console.log("New hour value: " + dateValue.getHours());
Original date: Tue Jan 12 2021 10:10:20 GMT+0530 (India Standard Time)
After adding 2 hours: Tue Jan 12 2021 12:10:20 GMT+0530 (India Standard Time)
New hour value: 12

Adding Different Time Units

var date = new Date("2021-01-12 10:10:20");

// Add 30 minutes
date.setMinutes(date.getMinutes() + 30);
console.log("After adding 30 minutes: " + date.getHours() + ":" + date.getMinutes());

// Add 45 seconds
date.setSeconds(date.getSeconds() + 45);
console.log("After adding 45 seconds: " + date.getSeconds());

// Add 5 days
date.setDate(date.getDate() + 5);
console.log("After adding 5 days: " + date.toDateString());
After adding 30 minutes: 12:40
After adding 45 seconds: 5
After adding 5 days: Sun Jan 17 2021

Handling Overflow

JavaScript automatically handles time overflow. For example, adding 25 hours will correctly increment the day:

var date = new Date("2021-01-12 23:30:00");
console.log("Original: " + date.toString());

// Add 2 hours (will overflow to next day)
date.setHours(date.getHours() + 2);
console.log("After adding 2 hours: " + date.toString());
Original: Tue Jan 12 2021 23:30:00 GMT+0530 (India Standard Time)
After adding 2 hours: Wed Jan 13 2021 01:30:00 GMT+0530 (India Standard Time)

Conclusion

Use setHours(), setMinutes(), and setSeconds() with their getter methods to add time to date strings. JavaScript automatically handles overflow between time units and dates.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements