Ashesh
Ashesh

Reputation: 17935

How to add days to Date?

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

Upvotes: 1785

Views: 2345348

Answers (30)

sparebytes
sparebytes

Reputation: 13136

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(); // not instatiated with date!!! DANGER
  result.setDate(date.getDate() + days);
  return result;
}

Proof / Example

Check this JsFiddle

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

// Bad Year/Month
function addDaysWRONG(date, days) {
    var result = new Date();
    result.setDate(date.getDate() + days);
    return result;
}

// Bad during DST
function addDaysDstFail(date, days) {
    var dayms = (days * 24 * 60 * 60 * 1000);
    return new Date(date.getTime() + dayms);    
}

// TEST
function formatDate(date) {
    return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
}

$('tbody tr td:first-child').each(function () {
    var $in = $(this);
    var $out = $('<td/>').insertAfter($in).addClass("answer");
    var $outFail = $('<td/>').insertAfter($out);
    var $outDstFail = $('<td/>').insertAfter($outFail);
    var date = new Date($in.text());
    var correctDate = formatDate(addDays(date, 1));
    var failDate = formatDate(addDaysWRONG(date, 1));
    var failDstDate = formatDate(addDaysDstFail(date, 1));

    $out.text(correctDate);
    $outFail.text(failDate);
    $outDstFail.text(failDstDate);
    $outFail.addClass(correctDate == failDate ? "right" : "wrong");
    $outDstFail.addClass(correctDate == failDstDate ? "right" : "wrong");
});
body {
    font-size: 14px;
}

table {
    border-collapse:collapse;
}
table, td, th {
    border:1px solid black;
}
td {
    padding: 2px;
}

.wrong {
    color: red;
}
.right {
    color: green;
}
.answer {
    font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <th colspan="4">DST Dates</th>
        </tr>
        <tr>
            <th>Input</th>
            <th>+1 Day</th>
            <th>+1 Day Fail</th>
            <th>+1 Day DST Fail</th>
        </tr>
        <tr><td>03/10/2013</td></tr>
        <tr><td>11/03/2013</td></tr>
        <tr><td>03/09/2014</td></tr>
        <tr><td>11/02/2014</td></tr>
        <tr><td>03/08/2015</td></tr>
        <tr><td>11/01/2015</td></tr>
        <tr>
            <th colspan="4">2013</th>
        </tr>
        <tr>
            <th>Input</th>
            <th>+1 Day</th>
            <th>+1 Day Fail</th>
            <th>+1 Day DST Fail</th>
        </tr>
        <tr><td>01/01/2013</td></tr>
        <tr><td>02/01/2013</td></tr>
        <tr><td>03/01/2013</td></tr>
        <tr><td>04/01/2013</td></tr>
        <tr><td>05/01/2013</td></tr>
        <tr><td>06/01/2013</td></tr>
        <tr><td>07/01/2013</td></tr>
        <tr><td>08/01/2013</td></tr>
        <tr><td>09/01/2013</td></tr>
        <tr><td>10/01/2013</td></tr>
        <tr><td>11/01/2013</td></tr>
        <tr><td>12/01/2013</td></tr>
        <tr>
            <th colspan="4">2014</th>
        </tr>
        <tr>
            <th>Input</th>
            <th>+1 Day</th>
            <th>+1 Day Fail</th>
            <th>+1 Day DST Fail</th>
        </tr>
        <tr><td>01/01/2014</td></tr>
        <tr><td>02/01/2014</td></tr>
        <tr><td>03/01/2014</td></tr>
        <tr><td>04/01/2014</td></tr>
        <tr><td>05/01/2014</td></tr>
        <tr><td>06/01/2014</td></tr>
        <tr><td>07/01/2014</td></tr>
        <tr><td>08/01/2014</td></tr>
        <tr><td>09/01/2014</td></tr>
        <tr><td>10/01/2014</td></tr>
        <tr><td>11/01/2014</td></tr>
        <tr><td>12/01/2014</td></tr>
        <tr>
            <th colspan="4">2015</th>
        </tr>
        <tr>
            <th>Input</th>
            <th>+1 Day</th>
            <th>+1 Day Fail</th>
            <th>+1 Day DST Fail</th>
        </tr>
        <tr><td>01/01/2015</td></tr>
        <tr><td>02/01/2015</td></tr>
        <tr><td>03/01/2015</td></tr>
        <tr><td>04/01/2015</td></tr>
        <tr><td>05/01/2015</td></tr>
        <tr><td>06/01/2015</td></tr>
        <tr><td>07/01/2015</td></tr>
        <tr><td>08/01/2015</td></tr>
        <tr><td>09/01/2015</td></tr>
        <tr><td>10/01/2015</td></tr>
        <tr><td>11/01/2015</td></tr>
        <tr><td>12/01/2015</td></tr>
    </tbody>
</table>

Upvotes: 1160

kodaq
kodaq

Reputation: 59

new Date(Date.now() + 2000 * 86400)

This snippet adds two days to the current date using the "2000" argument. You can tweak the number of days by updating the "2000" value in the second argument.

You can use this single line format to add days to the current date using the native JavaScript date.

Upvotes: 3

date d = new Date() // current date

date tomorrow = d.setMonth(d.getMonth(),d.getDate()+1) // return a date incremented by 0 months and 1 day

Upvotes: 2

Aldo
Aldo

Reputation: 923

Short:

function addDays(date, number) {
  const newDate = new Date(date);
  return new Date(newDate.setDate(newDate.getDate() + number));
}

console.log({
  tomorrow: addDays(new Date(), 1)
});

Advance:

function addDays(date, number) {
  const newDate = new Date(date);
  return new Date(newDate.setDate(date.getDate() + number));
}

function addMonths(date, number) {
  const newDate = new Date(date);
  return new Date(newDate.setMonth(newDate.getMonth() + number));
}

function addYears(date, number) {
  const newDate = new Date(date);
  return new Date(newDate.setFullYear(newDate.getFullYear() + number));
}

function getNewDate(dateTime) {
  let date = new Date();
  let number = parseInt(dateTime.match(/\d+/)[0]);

  if (dateTime.indexOf('-') != -1)
    number = (-number);

  if (dateTime.indexOf('day') != -1)
    date = addDays(date, number);
  else if (dateTime.indexOf('month') != -1)
    date = addMonths(date, number);
  else if (dateTime.indexOf('year') != -1)
    date = addYears(date, number);

  return date;
}

console.log({
  tomorrow: getNewDate('+1day'),
  yesterday: getNewDate('-1day'),
  nextMonth: getNewDate('+1month'),
  nextYear: getNewDate('+1year'),
});

With fix provide by jperl

Upvotes: 17

ejigsonpeter
ejigsonpeter

Reputation: 197

You can try:

var days = 50;

const d = new Date();

d.setDate(d.getDate() + days)

This should work well.

Upvotes: 16

Hasitha Amarathunga
Hasitha Amarathunga

Reputation: 2003

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 y = new Date();
y.setFullYear(y.getFullYear() + 5);

Upvotes: 82

Joel Coehoorn
Joel Coehoorn

Reputation: 416131

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 its 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.

Upvotes: 315

Jules
Jules

Reputation: 15

For everybody who don't know how to make it work : there is a full working code it's not perfect but you can copy past it and it's working.

In InDesign creat a .jsx in the startup scripts folder in "Program Files\Adobe\Adobe InDesign 2021\Scripts\startup scripts".

You can us the Extendscript Toolkit CC in the creative cloud to make it and paste this:

The restart indesign and jjmmyyyy+30 should be in the texte variable. this will show the date like this jj/m/yyyy idk how to make it show 24/07/2021 insted of 24/7/2021 but goodenough for me .

    #targetengine 'usernameVariable'
    function addVariables(openEvent) 
    {  
    var doc = openEvent.parent;  
    while ( doc.constructor.name != "Document" )  
      {  
    if ( doc.constructor.name == "Application" ){ return; }  
        doc = doc.parent;  
      }  
    // from http://stackoverflow.com/questions/563406/add-days-to-datetime


    var someDate = new Date();
    var numberOfDaysToAdd = 30;
    someDate.setDate(someDate.getDate() + numberOfDaysToAdd); 


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

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

      createTextVariable(doc, "jjmmyyyy+30", someFormattedDate);  
    }
    function createTextVariable(target, variableName, variableContents)  
    {  
    var usernameVariable = target.textVariables.itemByName(variableName);  
    if (!usernameVariable.isValid)  
      {  
        usernameVariable = target.textVariables.add();  
        usernameVariable.variableType = VariableTypes.CUSTOM_TEXT_TYPE;  
        usernameVariable.name = variableName;  
      }  
      usernameVariable.variableOptions.contents = variableContents;  
    }  
    app.addEventListener('afterOpen', addVariables);

Upvotes: -3

XMedia Software
XMedia Software

Reputation: 387

There is a problem with this kind of functions, I solve it with parseInt()

Date.prototype.addDays = function(dias) {

    var date = new Date(this.valueOf());
    date.setDate(parseInt(date.getDate()) + parseInt(dias));
    return date;
}

Date.prototype.addMonths = function(months) {
    var date = new Date(this.valueOf());
    date.setMonth(parseInt(date.getMonth()) + parseInt(months));
    return date;
}


Date.prototype.addYears = function(years) {
    var date = new Date(this.valueOf());
    date.setFullYear(parseInt(date.getFullYear()) + parseInt(years));
    return date;
}

Upvotes: 3

RameshD
RameshD

Reputation: 962

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)

`

Upvotes: 52

NicoESIEA
NicoESIEA

Reputation: 539

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

Upvotes: 23

Adriel O.S.
Adriel O.S.

Reputation: 21

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

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())

Upvotes: 0

AnthonyWJones
AnthonyWJones

Reputation: 189535

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.

Upvotes: 1833

Alexander Behling
Alexander Behling

Reputation: 627

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.

Upvotes: 12

sdgfsdh
sdgfsdh

Reputation: 37121

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.

Upvotes: 20

GuCier
GuCier

Reputation: 7425

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:

class MyCustomDate extends Date {

  addDays(days) {
    const date = new MyCustomDate(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
  }
  
}

const today = new MyCustomDate();

const nextWeek = today.addDays(7)

console.log(nextWeek)

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

Upvotes: 7

Clayton K. N. Passos
Clayton K. N. Passos

Reputation: 1372

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 {};

Upvotes: 1

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92697

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

new Date(+yourDate - 30 *86400000)

var yourDate=new Date();
var d = new Date(+yourDate - 30 *86400000) 

console.log(d)

Upvotes: 15

Dila Gurung
Dila Gurung

Reputation: 1784

As simple as this:

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

Upvotes: 12

makata
makata

Reputation: 2258

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'

Upvotes: 0

vaibhavmaster
vaibhavmaster

Reputation: 687

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

Upvotes: 16

Matteo Conta
Matteo Conta

Reputation: 1449

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

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

Upvotes: 9

sbrbot
sbrbot

Reputation: 6469

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.

Upvotes: 154

Rohit.007
Rohit.007

Reputation: 3502

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;

Upvotes: 13

Tuan
Tuan

Reputation: 715

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!

Upvotes: 2

John Slegers
John Slegers

Reputation: 47111

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 :

var DateHelper = {
    addDays : function(aDate, numberOfDays) {
        aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
        return aDate;                                  // Return the date
    },
    format : function format(date) {
        return [
           ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes
           ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes
           date.getFullYear()                          // Get full year
        ].join('/');                                   // Glue the pieces together
    }
}

// With this helper, you can now just use one line of readable code to :
// ---------------------------------------------------------------------
// 1. Get the current date
// 2. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));

(see also this Fiddle)

Upvotes: 5

LeMAK-Soft
LeMAK-Soft

Reputation: 35

try this

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

Upvotes: 0

Libu Mathew
Libu Mathew

Reputation: 2996

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

Upvotes: 1

Freewalker
Freewalker

Reputation: 7355

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

Upvotes: 4

Ronnie Smith
Ronnie Smith

Reputation: 18585

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

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

Upvotes: 0

Related Questions