开发者

Calculating a week's dates list starting from a given date

I need to get a given week's dates lis开发者_开发知识库t when a one date of that week and the starting day is given. Starting day may be Monday, Sunday etc.


Here is a way that I think works, not sure it's the most efficient way. $weekStart should be set to the day you consider the first of the week (0 = Sunday, 1 = Monday etc) and $date is the input date.

$weekStart = 0;
$date = '2011-06-1';

$timestamp = strtotime($date);

$dayOfWeek = date('N', $timestamp);

$startDate = mktime(0,0,0, date('n', $timestamp), date('j', $timestamp) - $dayOfWeek + $weekStart, date('Y', $timestamp));
$endDate = mktime(0,0,0, date('n', $timestamp), date('j', $timestamp) - $dayOfWeek + 6 + $weekStart, date('Y', $timestamp));

echo 'Week runs from ' . date('Y-m-d', $startDate) . ' to ' . date('Y-m-d', $endDate);


Replace $dayOfWeek = date('N', $timestamp); with $dayOfWeek = date('w', $timestamp); because if using a Sunday it was returning wrong week dates. Tested using $date = '2013-07-28'.

$weekStart = 0;
$date = '2011-06-1';

$timestamp = strtotime($date);

$dayOfWeek = date('w', $timestamp);

$startDate = mktime(0,0,0, date('n', $timestamp), date('j', $timestamp) - $dayOfWeek + $weekStart, date('Y', $timestamp));
$endDate = mktime(0,0,0, date('n', $timestamp), date('j', $timestamp) - $dayOfWeek + 6 + $weekStart, date('Y', $timestamp));

echo 'Week runs from ' . date('Y-m-d', $startDate) . ' to ' . date('Y-m-d', $endDate);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜