PHP: Get start and end dates of a week from date(‘W’) [转]
2012-07-10 16:03 tetang1230 阅读(343) 评论(0) 收藏 举报
PHP: Get start and end dates of a week from date(‘W’)
First off, from the PHP.net Manual, the ‘W’ inside the date() function returns the week number for a year.
Week
ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)
Example: 42 (the 42nd week in the year)
A quick example of date(‘W’)
<?php //October 29, 2009 is my birthday echo date('W', strtotime('2009-10-29')); //OUTPUT: 44 //October 29 is the 44th week in the year 2009
//Here is the function to get the start and end dates given a week number: function getWeekDates($year, $week, $start=true) { $from = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of monday in week $to = date("Y-m-d", strtotime("{$year}-W{$week}-7")); //Returns the date of sunday in week if($start) { return $from; } else { return $to; } //return "Week {$week} in {$year} is from {$from} to {$to}."; }
I did a couple of tests and so far the code worked okay. If you have a better way of doing it, post it below
PS: I got some of the code from a PHP.net comment and could no longer find the source. If you know the source, contact me.