Get n’th given day of any month

Based on recent requests i want to post this solution for getting the n’th given day of any month in any year.

For example the third Friday of current month:
[javascript]
<script type="text/javascript">
var myDay = getNthDayOfMonth(3,5,”,”);
alert(myDay);

/*
Parameters:
index: n’th occurrence of the specified day
day: daynumber – javascript way where sunday is 0 and is saturday is 6
month: javascript way which is 0-11 [optional – defaults to current]
year: Full year – four digits [optional – defaults to current]
*/
function getNthDayOfMonth(index,day,month,year){
// Create date object
var date = new Date();
// Set to first day of month
date.setDate(1);
// If supplied – set the month
if(month!==”&&month!==undefined){
// Set month
date.setMonth(month);
}else{
month = date.getMonth();
}
// If supplied – set the year
if(year!==”&&year!==undefined){
// Set year
date.setFullYear(year);
}else{
year = date.getFullYear();
}
// Find daynumber
firstDay = date.getDay();
// Find first friday.
while(date.getDay()!=day){
date.setDate(date.getDate()+1) ;
}
switch(index){
case 2:
date.setDate(date.getDate()+7);
break;
case 3:
date.setDate(date.getDate()+14);
break;
case 4:
date.setDate(date.getDate()+21);
break;
case 5:
date.setDate(date.getDate()+28);
if(date.getMonth()!==month){
date = null;
}
break;
}
return date;
}
</script>
[/javascript]

Alexander

3 thoughts on “Get n’th given day of any month”

  1. Great job again. I did find that the returned value is more than the date. It returns
    Day Mon date h:mm:ss EST YYYY
    for me to use this is sharepoint I have to format the date to m/d/yyyy. I tried to format the myDay var but it did not work, so at the end of the function before return date; I added this line

    	date = (date.getMonth(date)+1) + "/" + date.getDate(date) + "/" + date.getFullYear(date);
    
    

    This returns a date format that SP can use in it’s date field. Great job on both scripts.

    thanks again

    1. so now that I believe the output is formatted correctly m/d/yyyy, I cant seem to do much with the output. I need to get saturdays date also. Not always is the 3 friday going to proceed the 3 saturday. I thought adding one day to myDay would slove for this, but it is not.

      I tried this:
      [sourcecode]
      var myDay2 = myDay.setDate(myDay.getDate() + 1);

      Did I miss something in the date format, so the output is recognized as a date, or am I doing something wrong here adding a day to the output?

Leave a Reply