How to add/subtract dates with JavaScript?

252,453

Solution 1

Code:

var date = new Date('2011', '01', '02');
alert('the original date is ' + date);
var newdate = new Date(date);

newdate.setDate(newdate.getDate() - 7); // minus the date

var nd = new Date(newdate);
alert('the new date is ' + nd);

Using Datepicker:

$("#in").datepicker({
    minDate: 0,
    onSelect: function(dateText, inst) {
       var actualDate = new Date(dateText);
       var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
        $('#out').datepicker('option', 'minDate', newDate );
    }
});

$("#out").datepicker();​

JSFiddle Demo

Extra stuff that might come handy:

getDate()   Returns the day of the month (from 1-31)
getDay()    Returns the day of the week (from 0-6)
getFullYear()   Returns the year (four digits)
getHours()  Returns the hour (from 0-23)
getMilliseconds()   Returns the milliseconds (from 0-999)
getMinutes()    Returns the minutes (from 0-59)
getMonth()  Returns the month (from 0-11)
getSeconds()    Returns the seconds (from 0-59)

Good link: MDN Date

Solution 2

You need to use getTime() and setTime() to add or substract the time in a javascript Date object. Using setDate() and getDate() will lead to errors when reaching the limits of the months 1, 30, 31, etc..

Using setTime allows you to set an offset in milliseconds, and let the Date object figure the rest:

var now=new Date();
var yesterdayMs = now.getTime() - 1000*60*60*24*1; // Offset by one day;
now.setTime( yesterdayMs );

Solution 3

startdate.setDate(startdate.getDate() - daysToSubtract);


startdate.setDate(startdate.getDate() + daysToAdd);

Solution 4

The JavaScript Date object can help here.

The first step is to convert those strings to Date instances. That's easily done:

var str = "06/07/2012"; // E.g., "mm/dd/yyyy";
var dt = new Date(parseInt(str.substring(6), 10),        // Year
                  parseInt(str.substring(0, 2), 10) - 1, // Month (0-11)
                  parseInt(str.substring(3, 5), 10));    // Day

Then you can do all sorts of useful calculations. JavaScript dates understand leap years and such. They use an idealized concept of "day" which is exactly 86,400 seconds long. Their underlying value is the number of milliseconds since The Epoch (midnight, Jan 1st, 1970); it can be a negative number for dates prior to The Epoch.

More on the MDN page on Date.

You might also consider using a library like MomentJS, which will help with parsing, doing date math, formatting...

Solution 5

//In order to get yesterday's date in mm/dd/yyyy.


function gimmeYesterday(toAdd) {
            if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
            var d = new Date();
            d.setDate(d.getDate() - parseInt(toAdd));
var yesterDAY = (d.getMonth() +1) + "/" + d.getDate() + "/" + d.getFullYear();
$("#endDate").html(yesterDAY);
        }
$(document).ready(function() {
gimmeYesterday(1);
});

you can try here: http://jsfiddle.net/ZQAHE/

Share:
252,453
gregory boero.teyssier
Author by

gregory boero.teyssier

https://ali.actor

Updated on July 05, 2022

Comments

  • gregory boero.teyssier
    gregory boero.teyssier almost 2 years

    I want to let users easily add and subtract dates using JavaScript in order to browse their entries by date.

    The dates are in the format: "mm/dd/yyyy". I want them to be able to click a "Next" button, and if the date is: " 06/01/2012" then on clicking next, it should become: "06/02/2012". If they click the 'prev' button then it should become, "05/31/2012".

    It needs to keep track of leap years, number of days in the month, etc.

    Any ideas?

    P.S using AJAX to get the date from the server isn't an option, its a bit laggy and not the experience for the user that the client wants.

  • Valamas
    Valamas about 11 years
    dont stuff around with dates people. Just use moment.js and save your hair.
  • AndrewPK
    AndrewPK about 10 years
    I've seen times when moment.js calculates an invalid number of months during a date interval (diff) - for instance, between the dates of Feb 13, 2014 and Mar 15, 2016 - moment.js will report that there are 26 months when most languages with built in Date or DateTime classes of some sort will report this same interval as 25. XDate seems to calculate that interval correctly though.
  • Jack O'Neill
    Jack O'Neill about 10 years
    This is the only solution that worked for me. The Date constructor seems to behave strangely when a negative number is used for the day index. I found the only way to resolve it was to work with milliseconds directly
  • CSSian
    CSSian almost 10 years
    Why create a 3rd new date: var nd = new Date(newdate)?? The date object, newdate, as adjusted by .setDate is just fine, isn't it?
  • Tats_innit
    Tats_innit almost 10 years
    @KevinM yep, depends on the purpose so the nd is new date var was just created for clarity! :)
  • Karl Adler
    Karl Adler about 7 years
    Best solution!. All the other solutions using setDate should be downvoted... could have safed me a lot of trouble...
  • GR7
    GR7 almost 7 years
    Ditto. This is the cleanest and more reliable solution. Thank you @decasteljau
  • Diomidis Spinellis
    Diomidis Spinellis over 3 years
    It's 2020 and the MomentJS developers now consider it a legacy project.
  • T.J. Crowder
    T.J. Crowder over 3 years
    @DiomidisSpinellis - Hey, breaking news! :-) (Literally last month.) But note that it's not going anywhere, they just aren't adding any new features. They're still maintaining it. I haven't felt the need for a new feature in it in years, so... Anyway, hopefully Temporal moves forward at a good pace, but its API is still a (slightly) moving target...
  • Diomidis Spinellis
    Diomidis Spinellis over 3 years
    Agreed. No need to jump ship if you're already using MomentJS, but I wouldn't adopt it for a new project, unless there's a very compelling need.
  • Chris Hansen
    Chris Hansen about 3 years
    Also, JavaScript which isn't browser based (as in it is embedded in an application) may not have the library whitelisted; in those cases, knowing how to get the answer without the library is crucial.