views:

339

answers:

3

Hi,

I'm struggling with some javascript and date issues.

I would like to check if a given date is the first, second, third, fourth or last monday, tuesday, wednesday,..., sunday in the dates month.

The function should look like this:

if(checkdate(date, "second", "monday"))
{
   alert("This is the second monday of the month");
}
else
{
   alert("This is NOT the second monday of the month");
}

Any help would be nice!

Thanks in advance, Nick

+1  A: 

use getDate() to get day of the month

then getDay() to get the day of the week

using these two you should be able to accomplish your task. Refer to this http://www.w3schools.com/jsref/jsref_obj_date.asp

Pasta
+5  A: 

I would rather write a function that returns an object telling me the day and the week-number-in-month of the given date. Something like:

function infoDate(date) {
 return {
  day: date.getDay()+1,
  week: (date.getDate()-1)%7+1
 }
}

Then I can read the returned object and find out if it's the second monday or whatever:

var info = infoDate(date);
if(info.day==1 && info.week==2) {
  // second monday
}

Of course, you can still write another localized function that does exactly what you ask for based on an array of numeral and day names.

Alsciende
100% working code .. +1 :-)
infant programmer
thanks! works great this way!
Bundy
+1  A: 

It seems to me you only need to divide the date by 7 to know how many full weeks have passed, no matter what day it is. Subtracting one before dividing and adding it after sets the first week from 0 to one.

Date.prototype.weekofMonth= function(){
 return Math.floor((this.getDate()-1)/7)+1;
}
alert(new Date().weekofMonth())
kennebec