How to add / subtract dates using JavaScript?

I want users to easily add and subtract dates using JavaScript to view their entries by date.

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

It should track leap years, the number of days in a month, etc.

Any ideas?

A PS using AJAX to retrieve a date from a server is not an option; it is slightly behind, not the user experience that the client wants.

+62
javascript jquery date jquery-ui-datepicker
Jun 07 2018-12-12T00:
source share
12 answers

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

JSFiddle Demo

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

Additional materials that may come in 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 reference: MDN date

+82
Jun 07 '12 at 12:00
source share

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

Using setTime allows you to set the offset in milliseconds, and the remaining Date object does the rest:

 var now=new Date(); var yesterdayMs = now.getTime() - 1000*60*60*24*1; // Offset by one day; now.setTime( yesterdayMs ); 
+31
Aug 25 '13 at 1:33
source share
 startdate.setDate(startdate.getDate() - daysToSubtract); startdate.setDate(startdate.getDate() + daysToAdd); 
+14
Jun 07 '12 at 12:00
source share

The JavaScript Date object can help here.

The first step is to convert these strings to Date instances. This is easy to do:

 var str = "06/07/2012"; // Eg, "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 kinds of useful calculations. JavaScript dates understand leap years, etc. They use the idealized “day” concept, which is exactly 86,400 seconds. Their basic value is the number of milliseconds since the Age (midnight, January 1, 1970); this may be a negative number for dates prior to the era.

Read more on the MDN page on Date .

You can also use a library like MomentJS , which will help with parsing, performing date maths, formatting ...

+6
Jun 07 2018-12-12T00:
source share

Maybe this will 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);" /> 
+4
Jun 07 2018-12-12T00:
source share
 //In order to get yesterday 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/

+4
Nov 19 '12 at 16:16
source share

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

http://momentjs.com/

http://arshaw.com/xdate/

Violin:

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

+3
Jun 07 2018-12-12T00:
source share

As I like, 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 specific 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); 

Subtracting 0, you turn the date object into millisecond format.

+2
Mar 18 '15 at 11:05
source share

You can use your own javascript Date object to track dates. It will give you the current date, let you keep track of specific calendar data, and even help you manage different time zones. You can add and judge days / hours / seconds to change the date with which you work, or calculate new dates.

take a look at this object link to find out more:

Date

Hope this helps!

+1
Jun 07 2018-12-12T00:
source share

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

+1
Jan 13 '13 at 10:21
source share

Something I'm using (I need jquery), in my script I need this 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
Mar 02 '16 at 15:13
source share
 var date = new Date('your date string here'); // eg '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 for several months and years. I realized this by spending too much time searching for the getDate and setDate methods, trying to adapt to the month / year shifts.

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

0
Nov 21 '17 at 10:37
source share



All Articles