[javascript] 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?

This question is related to javascript date datetime time

The answer is


I use something like:

new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)

Works with day saving time:

new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

Works with new year:

new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

It can be parametrized:

function DateAdd(source, amount, step) {
  var factor = 1;
  if (step == "day") factor = 24 * 60 * 60 * 1000;
  else if (step == "hour") factor = 60 * 60 * 1000;
  ...
  new Date(source.getTime() + amount * factor);
}

    //the_day is 2013-12-31
    var the_day = Date.UTC(2013, 11, 31); 
    // Now, the_day will be "1388448000000" in UTC+8; 
    var the_next_day = new Date(the_day + 24 * 60 * 60 * 1000);
    // Now, the_next_day will be "Wed Jan 01 2014 08:00:00 GMT+0800"

There's a setDate and a getDate method, which allow you to do something like this :

var newDate = aDate.setDate(aDate.getDate() + numberOfDays);

If you want to both subtract a number of days and format your date in a human readable format, you should consider creating a custom DateHelper object that looks something like this :

_x000D_
_x000D_
var DateHelper = {_x000D_
    addDays : function(aDate, numberOfDays) {_x000D_
        aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays_x000D_
        return aDate;                                  // Return the date_x000D_
    },_x000D_
    format : function format(date) {_x000D_
        return [_x000D_
           ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes_x000D_
           ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes_x000D_
           date.getFullYear()                          // Get full year_x000D_
        ].join('/');                                   // Glue the pieces together_x000D_
    }_x000D_
}_x000D_
_x000D_
// With this helper, you can now just use one line of readable code to :_x000D_
// ---------------------------------------------------------------------_x000D_
// 1. Get the current date_x000D_
// 2. Add 20 days_x000D_
// 3. Format it_x000D_
// 4. Output it_x000D_
// ---------------------------------------------------------------------_x000D_
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));
_x000D_
_x000D_
_x000D_

(see also this Fiddle)


I created these extensions last night:
you can pass either positive or negative values;

example:

var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);


Date.prototype.addDays = function (num) {
    var value = this.valueOf();
    value += 86400000 * num;
    return new Date(value);
}

Date.prototype.addSeconds = function (num) {
    var value = this.valueOf();
    value += 1000 * num;
    return new Date(value);
}

Date.prototype.addMinutes = function (num) {
    var value = this.valueOf();
    value += 60000 * num;
    return new Date(value);
}

Date.prototype.addHours = function (num) {
    var value = this.valueOf();
    value += 3600000 * num;
    return new Date(value);
}

Date.prototype.addMonths = function (num) {
    var value = new Date(this.valueOf());

    var mo = this.getMonth();
    var yr = this.getYear();

    mo = (mo + num) % 12;
    if (0 > mo) {
        yr += (this.getMonth() + num - mo - 12) / 12;
        mo += 12;
    }
    else
        yr += ((this.getMonth() + num - mo) / 12);

    value.setMonth(mo);
    value.setYear(yr);
    return value;
}

the simplest answer is, assuming the need is to add 1 day to the current date:

var currentDate = new Date();
var numberOfDayToAdd = 1;
currentDate.setDate(currentDate.getDate() + numberOfDayToAdd );

To explain to you, line by line, what this code does:

  1. Create the current date variable named currentDate. By default "new Date()" automatically assigns the current date to the variable.
  2. Create a variable to save the number of day(s) to add to the date (you can skip this variable and use directly the value in the third line)
  3. Change the value of Date (because Date is the number of the month's day saved in the object) by giving the same value + the number you want. The switch to the next month will be automatic

Try

var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() +  (duration * 24 * 60 * 60 * 1000));

Using setDate() to add a date wont solve your problem, try adding some days to a Feb month, if you try to add new days to it, it wont result in what you expected.


Why so complicated?

Let's assume you store the number of days to add in a variable called days_to_add.

Then this short one should do it:

calc_date = new Date(Date.now() +(days_to_add * 86400000));

With Date.now() you get the actual unix timestamp as milliseconds and then you add as many milliseconds as you want to add days to. One day is 24h60min60s*1000ms = 86400000 ms or 864E5.


For those using Angular:

Just do:

$scope.booking.totTijd.setMinutes($scope.booking.totTijd.getMinutes()+15);
$scope.booking.totTijd.setDate($scope.booking.totTijd.getDate() + 1);

Our team considers date-fns the best library in this space. It treats dates as immutable (Moment.js will probably never adopt immutability), it's faster, and can be loaded modularly.

const newDate = DateFns.addDays(oldDate, 2);

I can't believe there's no cut'n'paste solution in this thread after 5 years!
SO: To get the same time-of-day regardless of summertime interference:

Date.prototype.addDays = function(days)
    {
    var dat = new Date( this.valueOf() )

    var hour1 = dat.getHours()
    dat.setTime( dat.getTime() + days * 86400000) // 24*60*60*1000 = 24 hours
    var hour2 = dat.getHours()

    if (hour1 != hour2) // summertime occured +/- a WHOLE number of hours thank god!
        dat.setTime( dat.getTime() + (hour1 - hour2) * 3600000) // 60*60*1000 = 1 hour

    return dat
or
    this.setTime( dat.getTime() ) // to modify the object directly
    }

There. Done!


You can create one with:-

_x000D_
_x000D_
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));
_x000D_
_x000D_
_x000D_

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.


Thanks Jason for your answer that works as expected, here is a mix from your code and the handy format of AnthonyWJones :

Date.prototype.addDays = function(days){
    var ms = new Date().getTime() + (86400000 * days);
    var added = new Date(ms);
    return added;
}

I guess I'll give an answer as well:
Personally, I like to attempt to avoid gratuitous variable declaration, method calls, and constructor calls, as they are all expensive on performance. (within reason, of course)
I was going to leave this as just comment under the Answer given by @AnthonyWJones but thought better of it.

// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
    return this.setTime( 864E5 * days + this.valueOf() ) && this;
};

// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
    return date.setTime( 864E5 * days + date.valueOf() ) && date;
};

// Basic Function declaration...
function addDaysToDate( date, days ) {
    return date.setTime( 864E5 * days + date.valueOf() ) && date;
};

The above will respect DST. Meaning if you add a number of days that cross DST, the displayed time (hour) will change to reflect that.
Example:
Nov 2, 2014 02:00 was the end of DST.

var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt );                  // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) );    // Tue Nov 11 2014 09:30:00

If you're looking to retain the time across DST (so 10:30 will still be 10:30)...

// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
    return this.setDate( this.getDate() + days ) && this;
};

// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
    return date.setDate( date.getDate() + days ) && date;
};

// Basic Function declaration...
function addDaysToDate( date, days ) {
    return date.setDate( date.getDate() + days ) && date;
};

So, now you have...

var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt );                  // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) );    // Tue Nov 11 2014 10:30:00

Generic prototype with no variables, it applies on an existing Date value:

Date.prototype.addDays = function (days) {
    return new Date(this.valueOf() + days * 864e5);
}

No, javascript has no a built in function, but you can use a simple line of code

timeObject.setDate(timeObject.getDate() + countOfDays);

Without using the second variable, you can replace 7 with your next x days:

let d=new Date(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));

Just spent ages trying to work out what the deal was with the year not adding when following the lead examples below.

If you want to just simply add n days to the date you have you are best to just go:

myDate.setDate(myDate.getDate() + n);

or the longwinded version

var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);

This today/tomorrow stuff is confusing. By setting the current date into your new date variable you will mess up the year value. if you work from the original date you won't.


My simple solution is:

nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);

this solution does not have problem with daylight saving time. Also, one can add/sub any offset for years, months, days etc.

day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);

is correct code.


My test exemple can do adition an minus in the same instance of Date Object.

_x000D_
_x000D_
Date.prototype.reset = function()
{
    let newDate = new Date(this.timeStamp)
    this.setFullYear        (newDate.getFullYear())
    this.setMonth           (newDate.getMonth())
    this.setDate            (newDate.getDate())
    this.setHours           (newDate.getHours())
    this.setMinutes     (newDate.getMinutes())
    this.setSeconds     (newDate.getSeconds())
    this.setMilliseconds    (newDate.getMilliseconds())
}

Date.prototype.addDays = function(days)
{
      this.timeStamp = this[Symbol.toPrimitive]('number')
      let daysInMiliseconds = (days * (1000 * 60 * 60 * 24))
      this.timeStamp = this.timeStamp + daysInMiliseconds
      this.reset()
}

Date.prototype.minusDays = function(days)
{
      this.timeStamp = this[Symbol.toPrimitive]('number')
      let daysInMiliseconds = (days * (1000 * 60 * 60 * 24))
      if(daysInMiliseconds <= this.timeStamp)
      {
          this.timeStamp = this.timeStamp - daysInMiliseconds
          this.reset()
      }
       
}

var temp = new Date(Date.now())// from now time

console.log(temp.toDateString())
temp.addDays(31)
console.log(temp.toDateString())
temp.minusDays(5)
console.log(temp.toDateString())
_x000D_
_x000D_
_x000D_


If you can, use moment.js. JavaScript doesn't have very good native date/time methods. The following is an example Moment's syntax:

_x000D_
_x000D_
var nextWeek = moment().add(7, 'days');_x000D_
alert(nextWeek);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
_x000D_
_x000D_
_x000D_

Reference: http://momentjs.com/docs/#/manipulating/add/


You can create your custom helper function here

function plusToDate(currentDate, unit, howMuch) {

    var config = {
        second: 1000, // 1000 miliseconds
        minute: 60000,
        hour: 3600000,
        day: 86400000,
        week: 604800000,
        month: 2592000000, // Assuming 30 days in a month
        year: 31536000000 // Assuming 365 days in year
    };

    var now = new Date(currentDate);

    return new Date(now + config[unit] * howMuch);
}

var today = new Date();
var theDayAfterTommorow = plusToDate(today, 'day', 2);

By the way, this is generic solution for adding seconds or minutes or days whatever you want.


Late to the party, but if you use jQuery then there's an excellent plugin called Moment:

http://momentjs.com/

var myDateOfNowPlusThreeDays = moment().add(3, "days").toDate();

http://momentjs.com/docs/#/manipulating/

And lots of other good stuff in there!

Edit: jQuery reference removed thanks to aikeru's comment


The mozilla docs for setDate() don't indicate that it will handle end of month scenarios. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date

setDate()

  • Sets the day of the month (1-31) for a specified date according to local time.

That is why I use setTime() when I need to add days.


I've used this approach to get the right date in one line to get the time plus one day following what people were saying above.

((new Date()).setDate((new Date()).getDate()+1))

I just figured I would build off a normal (new Date()):

(new Date()).getDate()
> 21

Using the code above I can now set all of that within Date() in (new Date()) and it behaves normally.

(new Date(((new Date()).setDate((new Date()).getDate()+1)))).getDate()
> 22

or to get the Date object:

(new Date(((new Date()).setDate((new Date()).getDate()+1))))

int days = 1;
var newDate = new Date(Date.now() + days * 24*60*60*1000);

CodePen

_x000D_
_x000D_
var days = 2;_x000D_
var newDate = new Date(Date.now() + days * 24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
_x000D_
_x000D_


You can use JavaScript, no jQuery required:

var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd); 
Formatting to dd/mm/yyyy :

var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();

var someFormattedDate = dd + '/'+ mm + '/'+ y;

The simplest approach that I have implemented is to use Date() itself. `

const days = 15; 
// Date.now() gives the epoch date value (in milliseconds) of current date 
nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000)

`


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

Be careful, because this can be tricky. When setting "tomorrow", it only works because it's current value matches the year and month for "today". However, setting to a date number like "32" normally will still work just fine to move it to the next month.


function addDays(n){
    var t = new Date();
    t.setDate(t.getDate() + n); 
    var month = "0"+(t.getMonth()+1);
    var date = "0"+t.getDate();
    month = month.slice(-2);
    date = date.slice(-2);
     var date = date +"/"+month +"/"+t.getFullYear();
    alert(date);
}

addDays(5);

The simplest solution.

_x000D_
_x000D_
 Date.prototype.addDays = function(days) {_x000D_
   this.setDate(this.getDate() + parseInt(days));_x000D_
   return this;_x000D_
 };_x000D_
_x000D_
 // and then call_x000D_
_x000D_
 var newDate = new Date().addDays(2); //+2 days_x000D_
 console.log(newDate);_x000D_
_x000D_
 // or_x000D_
_x000D_
 var newDate1 = new Date().addDays(-2); //-2 days_x000D_
 console.log(newDate1);
_x000D_
_x000D_
_x000D_


try this

function addDays(date,days) {        
      var one_day=1000*60*60*24; 
      return new Date(date.getTime()+(days*one_day)).toLocaleDateString(); 
    }

I had issues with daylight savings time with the proposed solution.

By using getUTCDate / setUTCDate instead, I solved my issue.

// Curried, so that I can create helper functions like `add1Day`
const addDays = num => date => {
  // Make a working copy so we don't mutate the supplied date.
  const d = new Date(date);

  d.setUTCDate(d.getUTCDate() + num);

  return d;
}

Correct Answer:

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

Incorrect Answer:

This answer sometimes provides the correct result but very often returns the wrong year and month. The only time this answer works is when the date that you are adding days to happens to have the current year and month.

// Don't do it this way!
function addDaysWRONG(date, days) {
  var result = new Date();
  result.setDate(date.getDate() + days);
  return result;
}

Proof / Example

Check this JsFiddle

_x000D_
_x000D_
// Correct_x000D_
function addDays(date, days) {_x000D_
    var result = new Date(date);_x000D_
    result.setDate(result.getDate() + days);_x000D_
    return result;_x000D_
}_x000D_
_x000D_
// Bad Year/Month_x000D_
function addDaysWRONG(date, days) {_x000D_
    var result = new Date();_x000D_
    result.setDate(date.getDate() + days);_x000D_
    return result;_x000D_
}_x000D_
_x000D_
// Bad during DST_x000D_
function addDaysDstFail(date, days) {_x000D_
    var dayms = (days * 24 * 60 * 60 * 1000);_x000D_
    return new Date(date.getTime() + dayms);    _x000D_
}_x000D_
_x000D_
// TEST_x000D_
function formatDate(date) {_x000D_
    return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();_x000D_
}_x000D_
_x000D_
$('tbody tr td:first-child').each(function () {_x000D_
    var $in = $(this);_x000D_
    var $out = $('<td/>').insertAfter($in).addClass("answer");_x000D_
    var $outFail = $('<td/>').insertAfter($out);_x000D_
    var $outDstFail = $('<td/>').insertAfter($outFail);_x000D_
    var date = new Date($in.text());_x000D_
    var correctDate = formatDate(addDays(date, 1));_x000D_
    var failDate = formatDate(addDaysWRONG(date, 1));_x000D_
    var failDstDate = formatDate(addDaysDstFail(date, 1));_x000D_
_x000D_
    $out.text(correctDate);_x000D_
    $outFail.text(failDate);_x000D_
    $outDstFail.text(failDstDate);_x000D_
    $outFail.addClass(correctDate == failDate ? "right" : "wrong");_x000D_
    $outDstFail.addClass(correctDate == failDstDate ? "right" : "wrong");_x000D_
});
_x000D_
body {_x000D_
    font-size: 14px;_x000D_
}_x000D_
_x000D_
table {_x000D_
    border-collapse:collapse;_x000D_
}_x000D_
table, td, th {_x000D_
    border:1px solid black;_x000D_
}_x000D_
td {_x000D_
    padding: 2px;_x000D_
}_x000D_
_x000D_
.wrong {_x000D_
    color: red;_x000D_
}_x000D_
.right {_x000D_
    color: green;_x000D_
}_x000D_
.answer {_x000D_
    font-weight: bold;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <th colspan="4">DST Dates</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>03/10/2013</td></tr>_x000D_
        <tr><td>11/03/2013</td></tr>_x000D_
        <tr><td>03/09/2014</td></tr>_x000D_
        <tr><td>11/02/2014</td></tr>_x000D_
        <tr><td>03/08/2015</td></tr>_x000D_
        <tr><td>11/01/2015</td></tr>_x000D_
        <tr>_x000D_
            <th colspan="4">2013</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>01/01/2013</td></tr>_x000D_
        <tr><td>02/01/2013</td></tr>_x000D_
        <tr><td>03/01/2013</td></tr>_x000D_
        <tr><td>04/01/2013</td></tr>_x000D_
        <tr><td>05/01/2013</td></tr>_x000D_
        <tr><td>06/01/2013</td></tr>_x000D_
        <tr><td>07/01/2013</td></tr>_x000D_
        <tr><td>08/01/2013</td></tr>_x000D_
        <tr><td>09/01/2013</td></tr>_x000D_
        <tr><td>10/01/2013</td></tr>_x000D_
        <tr><td>11/01/2013</td></tr>_x000D_
        <tr><td>12/01/2013</td></tr>_x000D_
        <tr>_x000D_
            <th colspan="4">2014</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>01/01/2014</td></tr>_x000D_
        <tr><td>02/01/2014</td></tr>_x000D_
        <tr><td>03/01/2014</td></tr>_x000D_
        <tr><td>04/01/2014</td></tr>_x000D_
        <tr><td>05/01/2014</td></tr>_x000D_
        <tr><td>06/01/2014</td></tr>_x000D_
        <tr><td>07/01/2014</td></tr>_x000D_
        <tr><td>08/01/2014</td></tr>_x000D_
        <tr><td>09/01/2014</td></tr>_x000D_
        <tr><td>10/01/2014</td></tr>_x000D_
        <tr><td>11/01/2014</td></tr>_x000D_
        <tr><td>12/01/2014</td></tr>_x000D_
        <tr>_x000D_
            <th colspan="4">2015</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>01/01/2015</td></tr>_x000D_
        <tr><td>02/01/2015</td></tr>_x000D_
        <tr><td>03/01/2015</td></tr>_x000D_
        <tr><td>04/01/2015</td></tr>_x000D_
        <tr><td>05/01/2015</td></tr>_x000D_
        <tr><td>06/01/2015</td></tr>_x000D_
        <tr><td>07/01/2015</td></tr>_x000D_
        <tr><td>08/01/2015</td></tr>_x000D_
        <tr><td>09/01/2015</td></tr>_x000D_
        <tr><td>10/01/2015</td></tr>_x000D_
        <tr><td>11/01/2015</td></tr>_x000D_
        <tr><td>12/01/2015</td></tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_


Old I know, but sometimes I like this:

function addDays(days) {
    return new Date(Date.now() + 864e5 * days);
}

I am using the following solution.

var msInDay = 86400000;
var daysToAdd = 5;
var now = new Date();
var milliseconds = now.getTime();
var newMillisecods = milliseconds + msInDay * daysToAdd;
var newDate = new Date(newMillisecods);
//or now.setTime(newMillisecods);

Date has a constructor that accepts an int. This argument represents total milliseconds before/after Jan 1, 1970. It also has a method setTime which does the same without creating a new Date object.

What we do here is convert days to milliseconds and add this value to the value provided by getTime. Finally, we give the result to Date(milliseconds) constructor or setTime(milliseconds) method.


to substract 30 days use (24h=86400000ms)

new Date(+yourDate - 30 *86400000)

_x000D_
_x000D_
var yourDate=new Date();_x000D_
var d = new Date(+yourDate - 30 *86400000) _x000D_
_x000D_
console.log(d)
_x000D_
_x000D_
_x000D_


Some implementations to extend Date https://gist.github.com/netstart/c92e09730f3675ba8fb33be48520a86d

/**
 * just import, like
 *
 * import './../shared/utils/date.prototype.extendions.ts';
 */
declare global {
  interface Date {
    addDays(days: number, useThis?: boolean): Date;

    addSeconds(seconds: number): Date;

    addMinutes(minutes: number): Date;

    addHours(hours: number): Date;

    addMonths(months: number): Date;

    isToday(): boolean;

    clone(): Date;

    isAnotherMonth(date: Date): boolean;

    isWeekend(): boolean;

    isSameDate(date: Date): boolean;

    getStringDate(): string;
  }
}

Date.prototype.addDays = function(days: number): Date {
  if (!days) {
    return this;
  }
  this.setDate(this.getDate() + days);
  return this;
};

Date.prototype.addSeconds = function(seconds: number) {
  let value = this.valueOf();
  value += 1000 * seconds;
  return new Date(value);
};

Date.prototype.addMinutes = function(minutes: number) {
  let value = this.valueOf();
  value += 60000 * minutes;
  return new Date(value);
};

Date.prototype.addHours = function(hours: number) {
  let value = this.valueOf();
  value += 3600000 * hours;
  return new Date(value);
};

Date.prototype.addMonths = function(months: number) {
  const value = new Date(this.valueOf());

  let mo = this.getMonth();
  let yr = this.getYear();

  mo = (mo + months) % 12;
  if (0 > mo) {
    yr += (this.getMonth() + months - mo - 12) / 12;
    mo += 12;
  } else {
    yr += ((this.getMonth() + months - mo) / 12);
  }

  value.setMonth(mo);
  value.setFullYear(yr);
  return value;
};

Date.prototype.isToday = function(): boolean {
  const today = new Date();
  return this.isSameDate(today);
};

Date.prototype.clone = function(): Date {
  return new Date(+this);
};

Date.prototype.isAnotherMonth = function(date: Date): boolean {
  return date && this.getMonth() !== date.getMonth();
};

Date.prototype.isWeekend = function(): boolean {
  return this.getDay() === 0 || this.getDay() === 6;
};

Date.prototype.isSameDate = function(date: Date): boolean {
  return date && this.getFullYear() === date.getFullYear() && this.getMonth() === date.getMonth() && this.getDate() === date.getDate();
};

Date.prototype.getStringDate = function(): string {
  // Month names in Brazilian Portuguese
  const monthNames = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
  // Month names in English
  // let monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  const today = new Date();
  if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay()) {
    return 'Hoje';
    // return "Today";
  } else if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay() + 1) {
    return 'Amanhã';
    // return "Tomorrow";
  } else if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay() - 1) {
    return 'Ontem';
    // return "Yesterday";
  } else {
    return this.getDay() + ' de ' + this.monthNames[this.getMonth()] + ' de ' + this.getFullYear();
    // return this.monthNames[this.getMonth()] + ' ' + this.getDay() + ', ' +  this.getFullYear();
  }
};


export {};

Use js-joda. It is an awesome immutable date and time library for javascript. Here is an excerpt from its cheat-sheet.

Add 17 days to today

LocalDate.now().plusDays(17); 

You can also build the desired date from now multiple operations at once.

LocalDate.now()
  .plusMonths(1)
  .withDayOfMonth(1)
  .minusDays(17); 

Or:

var d = LocalDate.parse('2019-02-23'); 
d.minus(Period.ofMonths(3).plusDays(3)); // '2018-11-20'

I sum hours and days...

Date.prototype.addDays = function(days){
    days = parseInt(days, 10)
    this.setDate(this.getUTCDate() + days);
    return this;
}

Date.prototype.addHours = function(hrs){
    var hr = this.getUTCHours() + parseInt(hrs  , 10);
    while(hr > 24){
      hr = hr - 24;
      this.addDays(1);
    }

    this.setHours(hr);
    return this;
}

2.39KB minified. One file. https://github.com/rhroyston/clock-js

_x000D_
_x000D_
console.log(clock.what.weekday(clock.now + clock.unit.days)); //"wednesday"_x000D_
console.log(clock.what.weekday(clock.now + (clock.unit.days * 2))); //"thursday"_x000D_
console.log(clock.what.weekday(clock.now + (clock.unit.days * 3))); //"friday"
_x000D_
<script src="https://raw.githubusercontent.com/rhroyston/clock-js/master/clock.min.js"></script>
_x000D_
_x000D_
_x000D_


Here is the way that use to add days, months, and years for a particular date in Javascript.

// To add Days
var d = new Date();
d.setDate(d.getDate() + 5);

// To add Months
var m = new Date();
m.setMonth(m.getMonth() + 5);

// To add Years
var m = new Date();
m.setFullYear(m.getFullYear() + 5);

The easiest way to get this done is using date-fns library.

var addDays = require('date-fns/add_days')
addDays(date, amount)

The documentation is available in this link here. You can also get this done using moment.js. The reference link is here

Hope it helps!


the same answer: How to add number of days to today's date?

    function DaysOfMonth(nYear, nMonth) {
        switch (nMonth) {
            case 0:     // January
                return 31; break;
            case 1:     // February
                if ((nYear % 4) == 0) {
                    return 29;
                }
                else {
                    return 28;
                };
                break;
            case 2:     // March
                return 31; break;
            case 3:     // April
                return 30; break;
            case 4:     // May
                return 31; break;
            case 5:     // June
                return 30; break;
            case 6:     // July
                return 31; break;
            case 7:     // August
                return 31; break;
            case 8:     // September
                return 30; break;
            case 9:     // October
                return 31; break;
            case 10:     // November
                return 30; break;
            case 11:     // December
                return 31; break;
        }
    };

    function SkipDate(dDate, skipDays) {
        var nYear = dDate.getFullYear();
        var nMonth = dDate.getMonth();
        var nDate = dDate.getDate();
        var remainDays = skipDays;
        var dRunDate = dDate;

        while (remainDays > 0) {
            remainDays_month = DaysOfMonth(nYear, nMonth) - nDate;
            if (remainDays > remainDays_month) {
                remainDays = remainDays - remainDays_month - 1;
                nDate = 1;
                if (nMonth < 11) { nMonth = nMonth + 1; }
                else {
                    nMonth = 0;
                    nYear = nYear + 1;
                };
            }
            else {
                nDate = nDate + remainDays;
                remainDays = 0;
            };
            dRunDate = Date(nYear, nMonth, nDate);
        }
        return new Date(nYear, nMonth, nDate);
    };

Very simple code to add days in date in java script.

_x000D_
_x000D_
var d = new Date();_x000D_
d.setDate(d.getDate() + prompt('how many days you want to add write here'));_x000D_
alert(d);
_x000D_
_x000D_
_x000D_


These answers seem confusing to me, I prefer:

var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);

getTime() gives us milliseconds since 1970, and 86400000 is the number of milliseconds in a day. Hence, ms contains milliseconds for the desired date.

Using the millisecond constructor gives the desired date object.


As simple as this:

new Date((new Date()).getTime() + (60*60*24*1000));

Edit: Instead of setTime() (or setHours()) you could do it this way:

Date.prototype.addDays= function(d){
  this.setDate(this.getDate() + d);
  return this;
};

var tomorrow = new Date().addDays(1);

Old:

Instead of using setTime() you can use setHours():

Date.prototype.addDays= function(d){
    this.setHours(this.getHours() + d * 24);
    return this;
};

var tomorrow = new Date().addDays(1);

See the JSFiddle...


Extending prototype in javascript may not be a good idea, especially in professional codebases.

What you want to do is extend the native Date class:

_x000D_
_x000D_
class MyCustomDate extends Date {_x000D_
_x000D_
  addDays(days) {_x000D_
    const date = new MyCustomDate(this.valueOf());_x000D_
    date.setDate(date.getDate() + days);_x000D_
    return date;_x000D_
  }_x000D_
  _x000D_
}_x000D_
_x000D_
const today = new MyCustomDate();_x000D_
_x000D_
const nextWeek = today.addDays(7)_x000D_
_x000D_
console.log(nextWeek)
_x000D_
_x000D_
_x000D_

This way, if one day Javascript implements a native addDays method, you won't break anything.


A solution designed for the pipeline operator:

const addDays = days => date => {
  const result = new Date(date);

  result.setDate(result.getDate() + days);

  return result;
};

Usage:

// Without the pipeline operator...
addDays(7)(new Date());

// And with the pipeline operator...
new Date() |> addDays(7);

If you need more functionality, I suggest looking into the date-fns library.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object