Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  62] [ 3]  / answers: 1 / hits: 105856  / 13 Years ago, sat, january 28, 2012, 12:00:00

I'm looking for a tested solid solution for getting current week of the year for specified date. All I can find are the ones that doesn't take in account leap years or just plain wrong. Does anyone have this type of stuff?



Or even better a function that says how many weeks does month occupy. It is usually 5, but can be 4 (feb) or 6 (1st is sunday and month has 30-31 days in it)



=================
UPDATE:



Still not sure about getting week #, but since I figured out it won't solve my problem with calculating how many weeks month occupy, I abandoned it.



Here's a function to find out how many weeks exactly month occupy on the calendar:



getWeeksNum: function(year, month) {
var daysNum = 32 - new Date(year, month, 32).getDate(),
fDayO = new Date(year, month, 1).getDay(),
fDay = fDayO ? (fDayO - 1) : 6,
weeksNum = Math.ceil((daysNum + fDay) / 7);
return weeksNum;
}

More From » date

 Answers
11
/**
* Returns the week number for this date. dowOffset is the day of week the week
* "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
* the week returned is the ISO 8601 week number.
* @param int dowOffset
* @return int
*/
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */

dowOffset = typeof(dowOffset) == 'number' ? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(),0,1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() -
(this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
var weeknum;
//if the year starts before the middle of a week
if(day < 4) {
weeknum = Math.floor((daynum+day-1)/7) + 1;
if(weeknum > 52) {
nYear = new Date(this.getFullYear() + 1,0,1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
}
else {
weeknum = Math.floor((daynum+day-1)/7);
}
return weeknum;
};

Usage:


var mydate = new Date(2011,2,3); // month number starts from 0
// or like this
var mydate = new Date('March 3, 2011');
alert(mydate.getWeek());

Source


[#87762] Thursday, January 26, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gabriel

Total Points: 323
Total Questions: 107
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
;