Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add days to JavaScript Date

How to add days to current Date using JavaScript? Does JavaScript have a built in function like .NET's AddDay()?

like image 459
Ashesh Avatar asked Feb 18 '09 23:02

Ashesh


People also ask

How do you add days to a date object?

The setDate() method can be used to add days to a date.

How do you add days in date in react JS?

Adding days to current Date const current = new Date(); Now, we can add the required number of days to a current date using the combination of setDate() and getDate() methods.

How do you sum days in JavaScript?

var today = new Date(); var tomorrow = new Date(); tomorrow. setDate(today. getDate()+1);


1 Answers

You can create one with:-

Date.prototype.addDays = function(days) {     var date = new Date(this.valueOf());     date.setDate(date.getDate() + days);     return date; }  var date = new Date();  console.log(date.addDays(5));

This takes care of automatically incrementing the month if necessary. For example:

8/31 + 1 day will become 9/1.

The problem with using setDate directly is that it's a mutator and that sort of thing is best avoided. ECMA saw fit to treat Date as a mutable class rather than an immutable structure.

like image 79
AnthonyWJones Avatar answered Oct 01 '22 22:10

AnthonyWJones