Jump to content

weeks in a year


poe

Recommended Posts

hi,

 

i found this snippet on php.net

For the week number for weeks starting on Sunday:

 

<?php

function week_of_year($month, $day, $year) {

 

$day_of_year = date('z', mktime(0, 0, 0, $month, $day, $year));

 

/* Days in the week before Jan 1. If you want weeks to start on Monday make this (x + 6) % 7 */

$days_before_year = date('w', mktime(0, 0, 0, 1, 1, $year));

 

$days_left_in_week = 7 - date('w', mktime(0, 0, 0, $month, $day, $year));

 

/* find the number of weeks by adding the days in the week before the start of the year, days up to $day, and the days left in this week, then divide by 7 */

return ($days_before_year + $day_of_year + $days_left_in_week) / 7;

 

}

?>

 

so if i go : week_of_year(1, 3, 2010)  (sunday)

 

the week shows as 1, because the script is set to begin new week on sunday,

 

however i am confused by his instruction " (x + 6) % 7 " to have the week start on a monday

 

what part of the script do i apply this equation ???

 

thanks

 

poe

Link to comment
https://forums.phpfreaks.com/topic/187804-weeks-in-a-year/
Share on other sites

however i am confused by his instruction " (x + 6) % 7 " to have the week start on a monday

 

The % operator is the modulo operator. It gives the division remainder.

 

You say that a divides b if there exist integers q and r such that b=qa and such that b >= q. If a does not divide b then b=qa+r for r != 0. The modulo operation returns what would be r.

 

So if Sunday = 0, then (0 + 6) % 7 = 6 because 6=0*7+6.

If Monday = 1, then (1 + 6) % 7 = 0 because 7=1*7+0.

If Tuesday = 2, then (2 + 6) % 7 = 1 because 8=1*7+1.

 

And so on...

 

So essentially, you have

Sunday = 0

Monday = 1

Tuesday = 2

Wednesday = 3

Thursday = 4

Friday = 5

Saturday = 6

 

Adding six to all of them and wrap when you reach 7:

Sunday = 6

Monday = 0

Tuesday = 1

Wednesday = 2

Thursday = 3

Friday = 4

Saturday = 5

 

Rearrange:

Monday = 0

Tuesday = 1

Wednesday = 2

Thursday = 3

Friday = 4

Saturday = 5

Sunday = 6

Link to comment
https://forums.phpfreaks.com/topic/187804-weeks-in-a-year/#findComment-991766
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.