faqts : Computers : Programming : Languages : JavaScript : Language Core : Dates

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes
Recently 1 of 1 people (100%) answered Yes

Entry

How I can I get (2nd Wed of month) from date object

Jan 25th, 2003 22:52
Eric Greenblatt, jsWalter,


// Returns the weekNumth dayNum of the month (e.g., the third Wednesday)
function getWeekdayDate(date, weekNum, dayNum)
{
	// we only want week numbers 1-5;
	// 5 also means "last" if there are only 4
	weekNum=(parseInt(weekNum)+4)%5+1;
	// and day numbers 0-6
	dayNum=parseInt(dayNum)%7;
	// get requested month
	var month=date.getMonth();
	// get new date based on requested date.
	var newDate=new Date(date.valueOf());
	// and set its day of the month to 1
	newDate.setDate(1);
	// get day of week of 1st of month
	var firstDayWeekday=newDate.getDay();
	// get day of month for requested day.
	var newWeekdayDate=(weekNum-1)*7+
	 (dayNum-firstDayWeekday+7)%7+1;
	// determine if day is past end of month
	// go one month ahead
	newDate.setMonth(newDate.getMonth()+1);
	// set day of month to 0
	// this sets date to last day of requested month
	newDate.setDate(0);
	// determine if found date is past end of month,
	// if so, go back a week (e.g., user requested 5th Thursday
	// in month when there were only 4
	var daysInMonth=newDate.getDate();
	if (newWeekdayDate>daysInMonth)
	{	newWeekdayDate-=7;
	}
	// set date of weekNumth dayNum
	newDate.setDate(newWeekdayDate);
	return newDate;
}
Date.prototype.getWeekdayDate=function(weekNum, dayNum)
 { return getWeekdayDate(this,weekNum,dayNum);};