2011-01-14 84 views
0

PHP计算周是周日 - 周六吗?对于给定的日期,我试图确定本周的开始和结束日期以及下一周/前几周的开始日期。一切都可以正常工作,除非我在星期天通过,它认为日期在前一周。计算指定日期的星期

$start = $_GET['start']; 
$year = date('Y', strtotime($start)); 
$week = date('W', strtotime($start)); 
$sunday = strtotime($year.'W'.$week.'0'); 

$next = strtotime('+7 Days', $sunday); 
$prev = strtotime('-7 Days', $sunday); 

echo '<p>week: ' . $week . '</p>'; 
echo '<p>sunday: ' . date('Y-m-d', $sunday) . '</p>'; 
echo '<p>next:' . date('Y-m-d', $next) . '</p>'; 
echo '<p>prev: ' . date('Y-m-d', $prev) . '</p>'; 

结果:

2011-01-09 (Sunday) 
Week: 01 
WRONG 

2011-01-10 (Monday) 
Week: 02 
RIGHT 

2011-01-15 (Saturday) 
Week: 02 
RIGHT 

回答

2

PHP根本不会考虑数周,如果你得到错误的结果,那是因为你的数学是关闭的。 :)

$date = strtotime('2011-1-14'); 
$startingSunday = strtotime('-' . date('w', $date) . ' days', $date); 
$previousSaturday = strtotime('-1 day', $startingSunday); 
$nextWeekSunday = strtotime('+7 days', $startingSunday); 
1

如ISO_8601定义,指的是什么date('W'),一个星期开始与周一

但要小心,并阅读了ISO-周:http://en.wikipedia.org/wiki/ISO_week_date

也许结果并不总是像预期。

例如:

date('W',mktime(0, 0, 0, 1, 1, 2011)) 

它会返回52,而不是01,因为一年的第一个ISO周是第一周,在给定的每年至少4天。
由于2011-1-1是星期六,因此只有2天,所以2011-1-1是2010年最后一周(52)的ISO,而不是2011年的第一周。

+0

感谢对于有用的信息,我认为现在的问题更清晰 – 2011-01-14 03:25:09

2

正如Dr.Molle指出的那样,关于“W”的信息是正确的。你的问题在这里:

$sunday = strtotime($year.'W'.$week.'0'); 
$sunday = strtotime($year.'W'.$week.'0'); 

$next = strtotime('+7 Days', $sunday); 
$prev = strtotime('-7 Days', $sunday); 

然后你在Timestamp对象上调用strtotime(对不起,我不知道确切的术语)。

错误的参数类型(时间戳和字符串使用不正确)是问题的原因。这里是我的一段代码,以确定一周和一周的开始日:

<?php 
$date = '2011/09/09'; 

while (date('w', strtotime($date)) != 1) { 

    $tmp = strtotime('-1 day', strtotime($date)); 
    $date = date('Y-m-d', $tmp); 

} 

$week = date('W', strtotime($date)); 

echo '<p>week: ' . $week . '</p>'; 

?> 

为了充分了解,你应该看看上date & strtotime手册。

1

函数日期('W')使用ISO-8601定义,因此星期一是一周中的第一天。

代替日期('W')使用strftime('%U')。

实施例:

$date = strtotime('2011-01-09'); 
echo strftime('%U',$date); 

结果:

02 

的代码:

$date = strtotime('2012-05-06'); 
$sunday = date('Y-m-d', strtotime(strftime("%Y-W%U-0", $date))); 
$sturday = date('Y-m-d', strtotime(strftime("%Y-W%U-6", $date))); 
echo $sunday . "\n"; 
echo $saturday; 

结果:

2012-05-06 
2012-05-12 
+0

非常感谢,我一直在学习英语,不要再写错了。 – 2012-10-30 00:02:04