说我想让一周开始和结束,例如:
Mon 29th June - week start
Sun 5th July - week end
and then tomorrow (Mon 6th July) it will say:
Mon 6th July - week start
Sun 12th July - week end
这是正确的方法吗?
$week_start = date('Y-m-d', strtotime('last monday'));
$week_end = date('Y-m-d', strtotime('this sunday'));
答案 0 :(得分:1)
DateTime类有一个名为setIsoDate()
的好方法:
$start = new DateTime();
$start->setIsoDate($start->format('o'), $start->format('W'));
$end = clone $start;
$end->modify('+6 day');
echo "From: " . $start->format('Y-m-d') . " to: " . $end->format('Y-m-d');
的 demo 强>
答案 1 :(得分:0)
如果当前日期是星期一,这将无法正常工作。然后last monday
会转换为上一周的星期一。
我会改用这种语法:
$week_start = date('Y-m-d', strtotime('last monday', strtotime('tomorrow')));
$week_end = date('Y-m-d', strtotime('this sunday'));
您也可以考虑避免使用这些“高级”相对格式,并根据当前工作日查找正确的日期。可能会更加可靠,因为那些周格式并不总是像人们预期的那样,并且它们背后的逻辑并不容易获得。
此解决方案使用更简单的strtotime
格式,而是将搜索逻辑放入代码本身。因此,如果不那么优雅,那就更容易预测了。
$weekday = date("N"); // 1 = Monday, 7 = Sunday
$week_start = date("Y-m-d", strtotime("-" . ($weekday - 1) . " days"));
$week_end = date("Y-m-d", strtotime("+" . (7 - $weekday) . " days"));
请注意,date("N")
标志仅在PHP 5.1及更高版本中可用。对于旧版本,您需要使用date("w")
,并将星期日值移至后面。
$weekday = date("w"); // 0 = Sunday, 6 = Saturday
if ($weekday == 0) {
$weekday = 7;
}