jQuery Datepicker previous complete months

Go To StackoverFlow.com

0

I'm using the Datepicker in two input fields to allow users to select a start and end date, respectively. I was curious if there's a setting for jQuery UI's datepicker to initialize the start date field to a period that is two complete months prior to the end date, which defaults to the current date. So when a user opens the page, the end date will be the current date and the start date will display the two complete months prior to the current date, e.g. end date is initialized to 4-3-2012, the start date would be 2-1-12.

I was going to write some custom formula to handle this, but wanted to be sure there wasn't already a setting for this built into the Datepicker.

2012-04-03 20:59
by kingrichard2005


0

$( ".selector" ).datepicker({"defaultDate":  ((today.getMonth() +11)%12) + "/01/" + today.getFullYear()});​

In order to "subtract 2" from the month, we add 11 and take the remainder because JS months are 0 based and we don't want to end up at -1 month.

edit: algorithm edited as per clarification

JsFiddle

2012-04-03 21:05
by Sinetheta
This starts the date at 2-3-12. What I'm trying to do is get the entire previous 2 months included, so for this example I would want it to show 2-1-12 - kingrichard2005 2012-04-03 21:18
Does that work for you instead then - Sinetheta 2012-04-03 21:56
That worked, thanks Sinetheta, I made a small fix, getYear() should be getFullYear(). Otherwise the year shows up as 112 instead of 2012 - kingrichard2005 2012-04-03 22:23
thanks, wasn't watching close enough I guess ; - Sinetheta 2012-04-03 23:36
Ads