Add Days (or Minutes, or Hours) to Javascript Date [or Subtract]

Add Days to Javascript Date

This article will explain how to add (or subtract) days, minutes, hours, seconds (etc.) to a JavaScript date.

Why would you want to do this? Perhaps you want to tell a user that their assignment is due in a week and provide the date, or maybe your application needs to know what the date was 30 days ago to pop up a reminder – there are near-infinite usage cases.

Add Days to Date Using Vanilla JavaScript

First, here’s how it’s done in plain old JavaScript:

var date = new Date(); // Todays date - the Date() constructor will default to the current date/time if no value is passed to it

var addDays = 4;
var addHours = 3;
var addMinutes = 2;
var addSeconds = 1;

// Add hours
// The getTime() method returns the number of milliseconds since January 1, 1970, so we can use it to alter the value of the date by any number of milliseconds
date.setTime(date.getTime() + (addHours * 60 * 60 * 1000)); // Convert hours to milliseconds - 60 minutes to an hour, 60 seconds to a minute, 1000 milliseconds to a second

// Add days
date.setTime(date.getTime() + (addDays * 24 * 60 * 60 * 1000)); // Similar to above, but additionally multiplying by 24 as there are 24 hours in a day

// Add minutes
date.setTime(date.getTime() + (addMinutes * 60 * 1000)); // Convert minutes to milliseconds

// Add seconds
date.setTime(date.getTime() + (addSeconds *  1000)); // Convert seconds to milliseconds

console.log(date);

The resulting date will be today’s date plus 4 days, 3 hours2 minutes, and 1 second.

You can supply negative numbers or use the (subtraction) operator instead of addition.

Add Days to Date Using Moment.js

If you build applications that deal with dates frequently, Moment.js is invaluable.

Moment.js provides the tools to manage dates, timezones, time periods (the period between two dates) – all conveniently wrapped in easily used classes. The documentation is great, and it simplifies date handling while making it more reliable.

Find it at:

https://momentjs.com/

For example, to add 3 days and 2 minutes to the current date you’d use:

moment().add(7, 'days').add(2, 'minutes');

Which is far easier to read and less mistake-prone than doing it in vanilla JavaScript.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *