73

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.

1
  • 1
    if you are using datepicker . then dateValue = $.datepicker.parseDate("mm/dd/yy", '06/01/2012'); dateValue.setDate(dateValue.getDate()+1); Jun 7, 2012 at 12:08

14 Answers 14

100

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

2
  • 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?
    – CSSian
    Jul 18, 2014 at 23:01
  • @KevinM yep, depends on the purpose so the nd is new date var was just created for clarity! :)
    – Tats_innit
    Jul 19, 2014 at 4:01
42

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 );
3
  • 2
    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 Mar 25, 2014 at 12:06
  • Best solution!. All the other solutions using setDate should be downvoted... could have safed me a lot of trouble...
    – Karl Adler
    Mar 30, 2017 at 11:30
  • Ditto. This is the cleanest and more reliable solution. Thank you @decasteljau
    – GR7
    Jul 24, 2017 at 16:06
15
startdate.setDate(startdate.getDate() - daysToSubtract);


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

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

5
  • 4
    dont stuff around with dates people. Just use moment.js and save your hair.
    – Valamas
    Mar 14, 2013 at 22:37
  • It's 2020 and the MomentJS developers now consider it a legacy project. Oct 15, 2020 at 15:47
  • 1
    @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... Oct 15, 2020 at 16:17
  • 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. Oct 16, 2020 at 17:18
  • 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. Mar 16, 2021 at 21:59
4
//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/

3

May be this could help

    <script type="text/javascript" language="javascript">
        function AddDays(toAdd) {
            if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
            var d = new Date();
            d.setDate(d.getDate() + parseInt(toAdd));

            document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
        }

function SubtractDays(toAdd) {
            if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
            var d = new Date();
            d.setDate(d.getDate() - parseInt(toAdd));

            document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
        }
    </script>
    ---------------------- UI ---------------
        <div id="result">
        </div>
        <input type="text" value="0" onkeyup="AddDays(this.value);" />
        <input type="text" value="0" onkeyup="SubtractDays(this.value);" />
3

Working with dates in javascript is always a bit of a hassle. I always end up using a library. Moment.js and XDate are both great:

http://momentjs.com/

http://arshaw.com/xdate/

Fiddle:

http://jsfiddle.net/39fWa/

var $output = $('#output'),
    tomorrow = moment().add('days', 1);

$('<pre />').appendTo($output).text(tomorrow);

tomorrow = new XDate().addDays(-1);

$('<pre />').appendTo($output).text(tomorrow);

1
  • 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.
    – AndrewPK
    Feb 14, 2014 at 3:23
2

The way I like, is if you have a date object you can subtract another date object from it to get the difference. Date objects are based on milliseconds from a certain date.

var date1 = new Date(2015, 02, 18); // "18/03/2015", month is 0-index
var date2 = new Date(2015, 02, 20); // "20/03/2015"

var msDiff = date2 - date1; // 172800000, this is time in milliseconds
var daysDiff = msDiff / 1000 / 60 / 60 / 24; // 2 days

So this is how you subtract dates. Now if you want to add them? date1 + date2 gives an error.. But if I want to get the time in ms I can use:

var dateMs = date1 - 0;
// say I want to add 5 days I can use
var days = 5;
var msToAdd = days * 24 * 60 * 60 * 1000; 
var newDate = new Date(dateMs + msToAdd);

By subtracting 0 you turn the date object into the milliseconds format.

2
var date = new Date('your date string here'); // e.g. '2017-11-21'

var newdate = new Date(date.getTime() + 24*60*60*1000 * days) // days is the number of days you want to shift the date by

This is the only solution that works reliably when adding/subtracting across months and years. Realized this after spending way too much time mucking around with the getDate and setDate methods, trying to adjust for month/year shifts.

decasteljau (in this thread) has already answered this but just want to emphasize the utility of this method because 90% of the answers out there recommend the getDate and setDate approach.

1

You can use the native javascript Date object to keep track of dates. It will give you the current date, let you keep track of calendar specific stuff and even help you manage different timezones. You can add and substract days/hours/seconds to change the date you are working with or to calculate new dates.

take a look at this object reference to learn more:

Date

Hope that helps!

1

All these functions for adding date are wrong. You are passing the wrong month to the Date function. More information about the problem : http://www.domdigger.com/blog/?p=9

1

The best date utility I've used is date-fns for a few reasons:

  • Uses the native JavaScript Date format.
  • Immutable; built using pure functions and always returns a new date instance instead of changing the passed one.
  • Modular; import just the functions you need.

Package manager:

"date-fns": "^1.30.1"

Code:

import { addDays, subDays } from 'date-fns'

let today = new Date()
let yesterday = subDays(today, 1)
let tomorrow = addDays(today, 1)

Simple and awesome.

0

Something I am using (jquery needed), in my script I need it for the current day, but of course you can edit it accordingly.

HTML:

<label>Date:</label><input name="date" id="dateChange" type="date"/>
<input id="SubtractDay" type="button" value="-" />
<input id="AddDay" type="button" value="+" />

JavaScript:

    var counter = 0;

$("#SubtractDay").click(function() {
    counter--;
    var today = new Date();
    today.setDate(today.getDate() + counter);
    var formattedDate = new Date(today);
    var d = ("0" + formattedDate.getDate()).slice(-2);
    var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
    var y = formattedDate.getFullYear();
    $("#dateChange").val(d + "/" + m + "/" + y);
});
$("#AddDay").click(function() {
    counter++;
    var today = new Date();
    today.setDate(today.getDate() + counter);
    var formattedDate = new Date(today);
    var d = ("0" + formattedDate.getDate()).slice(-2);
    var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
    var y = formattedDate.getFullYear();
    $("#dateChange").val(d + "/" + m + "/" + y);
});

jsfiddle

0

if you use the moment.js

examples:

moment(currentDate).add('days',3) // adds 3 days
moment(currentDate).subtract('days',3) // 3 days subtract

or

moment(currentDate).add('hours',3) // adds 3 hour
moment(currentDate).subtract('hours',3) // 3 hour subtract

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.