Sling Academy
Home/JavaScript/JavaScript: Adding a duration (days, hours) to a Date object

JavaScript: Adding a duration (days, hours) to a Date object

Last updated: February 19, 2023

This article shows you a couple of different ways to add a duration (days, hours, minutes, seconds) to a Date object in Javascript.

Using getTime() method

Imagine you are building a service that allows users to subscribe to a premium plan that lasts 15 days. When a user subscribes, you need to calculate the date when their subscription will expire so that you can restrict their access to the premium features or ask for renewal after that date. The code below shows you how to do that:

// Get the current date
const currentDate = new Date();

// Calculate the expired date 
// By adding 15 days to the current date
const expiredDate = new Date(currentDate.getTime() + 15 * 24 * 60 * 60 * 1000);

// Log current date and expired date in friendly format
console.log("Current date: ", currentDate.toDateString());
console.log("Expired date: ", expiredDate.toDateString());

15 * 24 * 60 * 60 * 1000 is exactly the number of milliseconds in 15 days.

Output:

Current date:  Thu Feb 16 2023
Expired date:  Fri Mar 03 2023

Using getDate(), setDate(), getHours(), setHours()

The example below calculates a time in the future that is 5 days, 9 hours, 30 minutes, and 30 seconds away:

// Get the current date
const date = new Date();
console.log('today: ', date.toLocaleString());

// add 5 days 
date.setDate(date.getDate() + 5);

// continuing adding 9 hours
date.setHours(date.getHours() + 9);

// continuing adding 30 minutes
date.setMinutes(date.getMinutes() + 30);

// continuing adding 30 seconds
date.setSeconds(date.getSeconds() + 30);

// print the result
console.log('result: ', date.toLocaleString());

Output:

today:  2/16/2023, 7:05:24 PM
result:  2/22/2023, 4:35:54 AM

In the code above, we have continuously mutated the original date object by adding days, hours, minutes, and seconds to it. The methods used are:

  • getDate() and setDate()
  • getHours() and setHours()
  • getMinutes() and setMinutes()
  • getSeconds() and setSeconds()

In addition, you can use the setMilliseconds() method and setMilliseconds() method if needed. However, very rarely do we have to care about these microscopic amounts of time.

Next Article: JavaScript: 2 Ways to Clone (Deep Copy) a Date Object

Previous Article: JavaScript: How to Check if 2 Date Ranges Overlap (2 Ways)

Series: Date and Time in JavaScript: Basic to Advanced Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration