Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add/subtract dates with JavaScript?

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.

like image 687
Ali Avatar asked Jun 07 '12 11:06

Ali


People also ask

Can I subtract dates in JavaScript?

Use the Math. abs() Function to Subtract Datetime in JavaScript.

How do you subtract days in JavaScript?

To subtract days to a JavaScript Date object, use the setDate() method. Under that, get the current days and subtract days. JavaScript date setDate() method sets the day of the month for a specified date according to local time.

Can you add two dates in JavaScript?

You need to convert the sum to a date. getTime() is in milliseconds since 1-1-1970. So you want to do. var ending = new Date(); ending.

How do you subtract in JavaScript?

The subtraction operator ( - ) subtracts the two operands, producing their difference.


1 Answers

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

like image 97
Tats_innit Avatar answered Sep 23 '22 08:09

Tats_innit