Where Were You On Monday, Week 32?

Here is an interesting problem: what is the timestamp of Monday, the ISO standard for the start of a week, for any week of any year? Knowing this may be important for calendaring or time framing.

To solve this, we will need to pull on the definition of how week one of any year is defined. The rule is the first week is the first week that contains a Thursday. Going off this rule, we can conclude that January 4th is always in the first week of the year.

Our strategy will then be getting the timestamp of January 4th for any year, which is easy, and then adding on 604800 seconds for each additional week. Then, after we are at the nth week of the year, we can easily ask strtotime() for "Monday this week".

Well, almost. A week in strtotime() is from Sunday to Saturday, which is different from the ISO standard of Monday to Sunday. So, take this year, 2009, and January 4th lands on a Sunday. This means that when we talk about "this week" in strtotime(), we are accidentally referring to what would be considered next week in ISO standards. Whoops. Luckily, for the convention of weeks being Sunday to Saturday, we can assert that the 3rd of January is always in the first week of the year.

function mondayOfWeekNo($weekNo, $year) {
  return strtotime('Monday this week', mktime(0,0,0,1,3,$year) + ($weekNo-1)*604800);
}

Pretty straight-forward right? We take one from $weekNo because mktime() already lands us on the first week. Getting to the 2nd week will just require mktime() + 1*604800.

Of course, we can generalize this to make it even more useful.

function dayOfWeekNo($day, $weekNo, $year) {
  return strtotime($day.' this week', mktime(0,0,0,1,3,$year) + ($weekNo-1)*604800);
}

Now we can determine the Monday, Friday, Thursday, or whatever of any week in any year. Just make sure that your conventional weeks match the ISO standard. If they do not, you will have to adjust your strategy to get this working. Have a better way to solve this problem? Leave a comment; I want to hear about it.


0 Responses to Where Were You On Monday, Week 32?

  1. There are currently no comments.

Leave a Reply



About

User