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.
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 hours, 2 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:
For example, to add 3 days and 2 minutes to the current date you’d use:
moment().add(7, 'days').add(2, 'minutes');