开发者

How to check/calculate the week-day count (using Date functions) using Javascript?

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
{
   开发者_如何学Calert("This is NOT the second monday of the month");
}


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.


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


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())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜