396

I need to be able to add 1, 2 , 5 or 10 days to today's date using jQuery.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Linda725
  • 3,997
  • 3
  • 16
  • 5

16 Answers16

638

You can use JavaScript, no jQuery required:

var someDate = new Date();
var numberOfDaysToAdd = 6;
var result = someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
console.log(new Date(result))
OldBuildingAndLoan
  • 2,801
  • 4
  • 32
  • 40
p.campbell
  • 98,673
  • 67
  • 256
  • 322
  • 121
    Like most things javascript, the built-in date processing is extremely powerful, but completely non-intuitive. – Joel Coehoorn Sep 29 '10 at 01:41
  • 10
    @Joel: agreed, it's a headshaker that `setDate()`. Non-intuitive is a good descriptor. – p.campbell Sep 29 '10 at 01:43
  • 5
    [Date object](https://developer.mozilla.org/en/JavaScript/Reference/global_objects/date) for reference. – Reigel Gallarde Sep 29 '10 at 01:43
  • @Joel: that problem is not exclusive to JavaScript. Date/Time API are traditionally a bit weird. – Thilo Sep 29 '10 at 01:45
  • how do i get it in dd/mm/yyyy format? – Linda725 Sep 29 '10 at 02:20
  • 18
    Just for documentation, you can add o substract days with the method `setDate`. It does not matter if the number you pass to the method is greater than 31, it could be even a negative value. – Cacho Santa Mar 08 '12 at 16:20
  • 1
    @Thilo: probably the final proof that humans have some problems in defining what is *time* ;) – superjos Mar 19 '13 at 00:55
  • 19
    I wouldn't call this *dd/mm/yyyy* format. I call this *d/m/yyyy*. – Sam May 22 '13 at 08:52
  • I'd +1 this 1000 times if I could. My little workaround for the dd issue is: if(dd < 10) { dd = "0" + dd; } – Aaron Liske Oct 23 '13 at 19:08
  • For your formatting to dd/mm/y, isn't this a primitive addition? If `someDate` is 2013-12-31 and you add a month, won't this make the date 2013/13/31? – jake Nov 16 '13 at 22:39
  • @jake No, it won't. `.getMonth()` returns a zero-based value for the month. So in your example, December would be returned as 11. The user would expect that it be 12, so we add 1 to the value returned by JavaScript. – p.campbell Nov 18 '13 at 15:49
  • 1
    If you have some troubles with adding days (which is the value of a – Guillaume Lhz Mar 11 '14 at 10:55
  • Apparently, you shouldn't use setDate directly because it's a mutator. http://stackoverflow.com/questions/563406/add-days-to-datetime – Jowen Jul 14 '14 at 11:18
  • I put this in a slightly different format: mm/dd/y :P – maudulus Aug 05 '14 at 17:00
  • How can I add numberOfDaysToAdd value dynamically.. – Santosh Domakonda Aug 26 '14 at 14:23
  • it will gets wrong when you add like 25+14 ? –  Jun 10 '15 at 12:04
  • To get Yesterday do this `d.setDate(d.getDate() - 1);` – mujaffars Jun 09 '16 at 07:08
  • An annoying gotcha: `.setDate()` returns an integer, and _not_ the underlying modified date object. So you can't use it for in-place mutation, like `{ cookieExpiry: new Date().setDate(new Date().getDate() + 30) }` – Lee Benson Nov 04 '16 at 14:10
  • 1
    If this method is returning the wrong date, try casting the number of days to add to an integer (using `parseInt()`) – Cellydy Jan 06 '17 at 15:52
165

This is for 5 days:

var myDate = new Date(new Date().getTime()+(5*24*60*60*1000));

You don't need JQuery, you can do it in JavaScript, Hope you get it.

Jacob
  • 3,598
  • 4
  • 35
  • 56
user3945851
  • 1,712
  • 1
  • 10
  • 5
111

You could extend the javascript Date object like this

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

and in your javascript code you could call

var currentDate = new Date();
// to add 4 days to current date
currentDate.addDays(4);
Rob Angelier
  • 2,335
  • 16
  • 29
Krishna Chytanya
  • 1,398
  • 1
  • 8
  • 12
87

Why not simply use

function addDays(theDate, days) {
    return new Date(theDate.getTime() + days*24*60*60*1000);
}

var newDate = addDays(new Date(), 5);

or -5 to remove 5 days

user3138856
  • 871
  • 6
  • 3
  • 1
    To return a formatted date use this **** return (returndate.getMonth() + 1) + "/" + returndate.getDate() + "/" + returndate.getFullYear(); – Sheikh M. Haris Jul 07 '14 at 01:55
  • 9
    this would fail twice a year due to DTS change. – jancha Apr 29 '15 at 09:56
  • As per jancha comment regarding this function: Adding days over DTS boundary will give you Incorrect Date/Time result. Thus, the best is to use established date library like momentjs. – br2000 May 15 '15 at 04:12
  • @jancha To be more precise, the code consistently adds 120 hours to the UTC equivalent time -- this means, that twice a year, you would end up with a different hour-of-the-day in the result. This might be what you want, or it might not. – minexew Jan 04 '21 at 13:34
37

[UPDATE] Consider reading this before you proceed...

Moment.js

Install moment.js from here.

npm : $ npm i --save moment

Bower : $ bower install --save moment

Next,

var date = moment()
            .add(2,'d') //replace 2 with number of days you want to add
            .toDate(); //convert it to a Javascript Date Object if you like

Link Ref : http://momentjs.com/docs/#/manipulating/add/

Moment.js is an amazing Javascript library to manage Date objects

Good Luck.

Aakash
  • 21,375
  • 7
  • 100
  • 81
35

Pure JS solution, with date formatted YYYY-mm-dd format

var someDate = new Date('2014-05-14');
someDate.setDate(someDate.getDate() + 15); //number  of days to add, e.x. 15 days
var dateFormated = someDate.toISOString().substr(0,10);
console.log(dateFormated);
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Tomas Šivickas
  • 977
  • 9
  • 10
  • 1
    Excellent... esp. the way of formatting which perfectly works in my case, may not be a generic solution though. – Fr0zenFyr May 20 '16 at 11:16
  • Parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. (from the Mozilla ref) – Chris Jun 23 '20 at 09:02
  • 1
    when days value come dynamic then your code create the wrong date, please check – Siraj Ali Jun 17 '21 at 12:33
31

The prototype-solution from Krishna Chytanya is very nice, but needs a minor but important improvement. The days param must be parsed as Integer to avoid weird calculations when days is a String like "1". (I needed several hours to find out, what went wrong in my application.)

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

Even if you do not use this prototype function: Always be sure to have an Integer when using setDate().

Erik Aderhold
  • 448
  • 1
  • 6
  • 13
  • 1
    I had written the prototype function myself but it just wouldn't work when adding days and I could not figure it out. Adding parseInt solved this problem immediately. How did you think to use that? I never would've thought of that in a million years. – Nathaniel Hoyt Apr 23 '18 at 00:07
18

If the times in the Date are not needed, then you can simply use the date object's methods to extract the Month,Year and Day and add "n" number of days to the Day part.

var n=5; //number of days to add. 
var today=new Date(); //Today's Date
var requiredDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()+n)

Ref:Mozilla Javascript GetDate

Edit: Ref: Mozilla JavaScript Date

Sahil J
  • 685
  • 6
  • 10
  • 1
    If you run a getDate() function on requiredDate, the returned value with then be incorrect. – Cyrille Armanger Jun 29 '15 at 09:32
  • 1
    Not really @CyrilleArmanger : Check this http://jsfiddle.net/sahiljambhekar/6u7caake/ . Also on the variable 'requiredDate' if you run the getDate() method then it would return the Day of the Month,which comes in correct too. So please,remove the downvote as it's working code – Sahil J Jul 15 '15 at 20:25
  • 4
    What will happen when today.getDate() === 30? – Alex Polkhovsky Dec 27 '16 at 01:24
  • @AlexPolkhovsky: Sorry for the late reply. In your case, it would roll over to the next month (if that month has 30 days). Ref: https://jsfiddle.net/sahiljam/jmty86xm/ – Sahil J Feb 18 '18 at 03:19
  • this method cannot work. What happens if the date === 30 – Joshua Oluikpe Apr 19 '20 at 06:28
16

The accepted answer here gave me unpredictable results, sometimes weirdly adding months and years.

The most reliable way I could find was found here Add days to Javascript Date object, and also increment month

var dayOffset = 20;
var millisecondOffset = dayOffset * 24 * 60 * 60 * 1000;
december.setTime(december.getTime() + millisecondOffset); 

EDIT: Even though it has worked for some people, I don't think it is entirely correct. I would recommend going with a more popular answer or using something like http://momentjs.com/


Community
  • 1
  • 1
Mulhoon
  • 1,852
  • 21
  • 26
  • 1
    This won't work for days with daylight savings changing. Some days aren't 24 hours a day, some are 23, some are 25. I don't know what unpredictable results you got but adding 1 to the day(date) property and let the library work out the rest is usually the best way. – dalore Nov 20 '12 at 16:52
  • If you are only interested in which **day** it is could use this solution make sure that the time is something like 12:00. You need to ignore the time of the result though, but the day should be correct. – Mikael Vandmo May 02 '13 at 08:50
  • 1
    What are the unpredictable results? – Sam May 22 '13 at 08:51
  • @Sam Sounds like "unpredictable results" == "adding 31 days adds a month"...at least that's what it sounds like to me from he comment. – saluce May 22 '13 at 14:29
  • 1
    @saluce, I know what you mean, but I don't think I've ever had such problems from the accepted answer's method. I'm curious about whether there really were incorrect results or if this answer is incorrect. – Sam May 22 '13 at 22:46
10

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);
Libu Mathew
  • 2,976
  • 23
  • 30
8
Date.prototype.addDays = function(days)
{
    var dat = new Date(this.valueOf() + days * 24 * 60 * 60 * 1000 );
    return dat;
}
Eren Demir
  • 119
  • 1
  • 4
4

You can use this library "Datejs open-source JavaScript Date Library".

andres descalzo
  • 14,887
  • 13
  • 64
  • 115
4

I've found this to be a pain in javascript. Check out this link that helped me. Have you ever thought of extending the date object.

http://pristinecoder.com/Blog/post/javascript-formatting-date-in-javascript

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};
sleath
  • 871
  • 1
  • 13
  • 42
  • Dead link... Fortunately page was saved on [WayBack Machine](https://web.archive.org/web/20120329060501/http://www.stevenleath.com/blogengine.web/post/2011/03/09/How-do-I-add-subtract-days-in-javascript.aspx). Although, there isn't much useful information on the page than the answer, it's good to have a look at the referenced source. – Fr0zenFyr May 20 '16 at 11:22
1

you can try this and don't need JQuery: timeSolver.js

For example, add 5 day on today:

var newDay = timeSolver.add(new Date(),5,"day");

You also can add by hour, month...etc. please see for more infomation.

sean1093
  • 109
  • 1
  • 3
0

I found that JavaScript can return a correct date when you use new Date(nYear, nMonth, nDate); with the over days of that month. Try to see the result of a dDate variable when you use this:

var dDate = new Date(2012, 0, 34); // the result is 3 Feb 2012


I have a SkipDate function to share:

    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);
    };
Sam
  • 86,580
  • 20
  • 181
  • 179
0

Here is a solution that worked for me.

function calduedate(ndays){

    var newdt = new Date(); var chrday; var chrmnth;
    newdt.setDate(newdt.getDate() + parseInt(ndays));

    var newdate = newdt.getFullYear();
    if(newdt.getMonth() < 10){
        newdate = newdate+'-'+'0'+newdt.getMonth();
    }else{
        newdate = newdate+'-'+newdt.getMonth();
    }
    if(newdt.getDate() < 10){
        newdate = newdate+'-'+'0'+newdt.getDate();
    }else{
        newdate = newdate+'-'+newdt.getDate();
    }

    alert("newdate="+newdate);

}
Flexo
  • 87,323
  • 22
  • 191
  • 272
Nadeem
  • 1
  • 1