Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to Get Calendar Week from Date.

Status
Not open for further replies.

awolff01

Programmer
Jun 17, 2003
55
US
I need to determine what week of the year it is.

For example..01/01/2004 is in week 1
01/31/2004 is in week 5.

Does'nt look like Javascript has a pre-built function for this? Anybody know how to accomplish this?

I was thinking perhaps determinining what day of the year it is (1-365) and then dividing by 7. But I dont think javascript has a method for that either.

Thanks.

 
This might work for you. Define Week 1 by plugging in the last day of that week then hand a date to WeekofYear() and get back a week number relative to Week 1.

Code:
  var gWeekMs  = 1000 * 60 * 60 * 24 * 7;

// initialize to Saturday 3 Jan 2004
  var gWeekOneMs = Date.UTC(2004,0,3);
  var gLastDay   = new Date(2004,0,3).getDay();

// calculate # days until end of week
function calcEndofWeek(dd) {
  var tLastDay = (gLastDay >= dd) ? gLastDay : gLastDay + 7;
  return (tLastDay - dd);
}

// calculate week of the year
function WeekofYear(m0,d,y) {
  tDate  = new Date(y,m0,d);
  tAdj   = calcEndofWeek(tDate.getDay());
  tAdjMs = Date.UTC(y,m0,d+tAdj);
  return ((tAdjMs - gWeekOneMs) / gWeekMs) + 1;
}

The Date() object has some quirks. Note that Month is specified relative 0, Day and Year relative 1. Also, the Date.UTC() calls sidestep a nasty Daylight Savings Time feature/bug.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top