Jump to content

Unix timestamp of week numbers


nico1234

Recommended Posts

I want to have the  timestamps  of  week numbers, this is working perfectly from the year 2011 to  2012.  It refuses to switch to the year 2013. 

Do anyone know what i'm doing wrong?:

 

<?php

 

$year='2012';

$weekno='01';

$date = strtotime($year.'W'.$weekno);

 

for($i=0;$i<55;$i++){

        print date('d-m-Y W',$date)."\n";

        $date=(weekno($date,'1'))."\n";

        $date=(int)$date;

}

 

 

function weekno($date,$step=''){

        $year=date('Y',$date);

      $weekno=date('W',$date);

        $date = strtotime($year.'W'.$weekno);

        if($step>0){

                $date = strtotime($year.'W'.$weekno. '+1 week');

        }

        if($step<0){

                $date = strtotime($year.'W'.$weekno. '-1 week');

        }

      return($date);

 

}

 

 

?>

 

 

Link to comment
Share on other sites

There's no need to use strtotime(+1 week). You can add or subtract a week from a timestamp using

 

60*60*24*7 or 604800.

 

That's 60 seconds times 60 minutes times 24 hours times 7 days.

 

This can be accomplished much faster using math.

 

<?php

$year='2015';

// Used from http://php.net/manual/en/function.date.php#85332
$stamp = strtotime($year.'W010');

// Determine if the year has 52 or 53 weeks.
// First we calculate the timestamp 53 weeks from the start
$week53 = $stamp + (604800*53);
// We then use the date function to get the week number of that timestamp
$week53num = date( 'W', $week53 );
// If the week number is 53, the year has 53 weeks
if( $week53num == '53' ) {
$max = 53;
// Otherwise, it only has 52
} else {
$max = 52;
}

// We loop through weeks, starting at 0 and ending at either 51, or 52 depending on the value of $max
for( $week = 0; $week < $max; $week++ ) {
// We multiply the number of seconds in a week with the current week number to get the timestamp for that week
$weekstamp = $stamp + ( 604800*$week );
// We use the calculated timestamp in the date function to output the formatted date.
echo 'Week '.($week+1).' is on '.date('d-m-y',$weekstamp).'<br>';
}


?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.