简体   繁体   English

给定日期的一周的开始和结束

[英]start and end of the week by given date

Is there a short preset function to find the start ( Monday ) and end ( Sunday ) of the week by a given $date ? 是否有一个简短的预设功能来查找给定$date的一周的开始( 星期一 )和结束( 星期日 )?

I tried: 1) 我试过了:1)

date("Y-m-d", strtotime('sunday this week ' . $date));
date("Y-m-d", strtotime('monday this week ' . $date));

But this fails when $date is Sunday... it returns the Monday of Next week. 但这在$date是星期日时失败了……它返回下一周的星期一。

2) also this 2)也是这个

date("Y-m-d", strtotime('last monday ' . $date));
date("Y-m-d", strtotime('next sunday ' . $date));

But again if $date is Monday or Sunday it gives the previous/next week. 但是,如果$date是星期一或星期天,则给出上一个/下一个星期。

I know it can be done with few condition .. but I m look for more out of the box solution. 我知道可以在很少条件下完成此操作..但我正在寻找更多现成的解决方案。

You can use DateTime::format('N') to get the ISO-8601 day of the week (1 = Monday .. 7 = Sunday) and do some simple date arithmetic to get the Monday and the Sunday of the week that contains the specified date (I assume you want the week starting on Monday). 您可以使用DateTime::format('N')来获取ISO-8601的星期几(1 =星期一.. 7 =星期日),并执行一些简单的日期算术来获取包含以下内容的一周的星期一和星期日指定的日期(我想您要从星期一开始的一周)。

// Today (or any other day you like)
$today = new DateTime('now');
echo('Today:  '.$today->format('Y-m-d (D)')."\n");

// Day of week (1 = Monday .. 7 = Sunday)
$dow = $today->format('N');

// Monday is ($dow-1) days in the past
$monday = clone $today;
$monday->sub(new DateInterval('P'.($dow-1).'D'));
echo('Monday: '.$monday->format('Y-m-d')."\n");

// Sunday is 6 days after Monday
$sunday = clone $monday;
$sunday->add(new DateInterval('P6D'));
echo('Sunday: '.$sunday->format('Y-m-d')."\n");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM