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.
Advertisement
Answer
Code:
JavaScript
x
8
1
var date = new Date('2011', '01', '02');
2
alert('the original date is ' + date);
3
var newdate = new Date(date);
4
5
newdate.setDate(newdate.getDate() - 7); // minus the date
6
7
var nd = new Date(newdate);
8
alert('the new date is ' + nd);
Using Datepicker:
JavaScript
1
11
11
1
$("#in").datepicker({
2
minDate: 0,
3
onSelect: function(dateText, inst) {
4
var actualDate = new Date(dateText);
5
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
6
$('#out').datepicker('option', 'minDate', newDate );
7
}
8
});
9
10
$("#out").datepicker();•
11
Extra stuff that might come handy:
JavaScript
1
9
1
getDate() Returns the day of the month (from 1-31)
2
getDay() Returns the day of the week (from 0-6)
3
getFullYear() Returns the year (four digits)
4
getHours() Returns the hour (from 0-23)
5
getMilliseconds() Returns the milliseconds (from 0-999)
6
getMinutes() Returns the minutes (from 0-59)
7
getMonth() Returns the month (from 0-11)
8
getSeconds() Returns the seconds (from 0-59)
9
Good link: MDN Date