View Full Version : Correct Day, for Month

12-08-2009, 06:27 AM
How can I change the day when the user select a month?
When they select Feb ->29 days, select May -> 31 days.

Like what facebook does.

Old Pedant
12-08-2009, 06:42 AM
// we will suppose that you have a <select> for the year and one for the <month>
var form = document.YourFormName;
var yr = form.yearSelect[form.yearSelect.selectedIndex].value; // any valid 4 digit year
var mn = form.yearSelect[form.monthSelect.selectedIndex].value; // 1 - 12

var firstOfNextMonth = new Date( yr, mn, 1 ); // in JS month goes 0 to 11, so this works
var lastOfGivenMonth = new Date( firstOfNextMonth.getTime() - 24 * 60 *60 * 1000 );

var lastDayOfGivenMonth = lastOfGivenMonth.getDate();

Note: without the year, you can't get the right number of days for February. Though of course it would work for any other month with any year.

12-08-2009, 08:36 AM
Dates, unlike months and weekdays are not 0 based.

The last day of a month is the zeroth day of the next month.

var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();

var d=new Date();

var M= ['Jan','Feb','Mar','Apr','May','Jun','Jul',
i= 0, y= 2012, A= [], d= new Date(y, 0, 1);
A[i]= M[i]+' has '+d.daysinMonth()+' days';
alert('Days in each Month of '+y+'\n\t'+A.join('\n\t'))

12-08-2009, 11:48 AM
Check out the OO Dropdown Date Picker script from my sig. Scroll down to post #15 for the latest version.

Old Pedant
12-08-2009, 07:27 PM
Never tried using 0 for last-day-of-prior month. Had a hunch it would work, but hadn't tested it so gave the next-best answer.

It works with DateSerial() in VB/VBS/Access, by the by, if anybody cares.