只要将星期几的名称与我们一起使用,而不必在“ this”前加一个,便可以获取一周中的第一天。
$dt=new \DateTime('7/16/2019');
echo $dt->format('l jS \of F Y h:i:s A').PHP_EOL; //Tuesday 16th of July 2019 12:00:00 AM
echo (clone $dt)->modify('monday')->format('l jS \of F Y h:i:s A').PHP_EOL; //Monday 22nd of July 2019 12:00:00 AM
echo (clone $dt)->modify('tuesday')->format('l jS \of F Y h:i:s A').PHP_EOL; //Tuesday 16th of July 2019 12:00:00 AM
echo (clone $dt)->modify('wednesday')->format('l jS \of F Y h:i:s A').PHP_EOL; //Wednesday 17th of July 2019 12:00:00 AM
如何才能获得上一个工作日?例如,
请注意,previous
将在除返回Tuesday 9th of July 2019 12:00:00 AM
的星期二以外的所有时间工作。
答案 0 :(得分:0)
尝试一下:
$dt=new \DateTime('7/16/2019 00:01:00');
$dt->modify('monday');
echo $dt->format('l jS \of F Y h:i:s A').PHP_EOL; //Tuesday 16th of July 2019 12:00:00 AM
echo (clone $dt)->modify('previous monday')->format('l jS \of F Y h:i:s A').PHP_EOL; //Monday 22nd of July 2019 12:00:00 AM
echo (clone $dt)->modify('previous tuesday')->format('l jS \of F Y h:i:s A').PHP_EOL; //Tuesday 16th of July 2019 12:00:00 AM
echo (clone $dt)->modify('previous wednesday')->format('l jS \of F Y h:i:s A').PHP_EOL;
我将其设置为下一个星期一,因此上一个总是返回您期望的结果。
答案 1 :(得分:0)
您可以使用包装器功能来检查DateTime实例的工作日。如果工作日与实例相同,则只需返回实例的副本。
function getPreviousWeekday(DateTime $dt, string $weekday)
{
if (strtolower($dt->format('l')) == strtolower($weekday)) {
return clone $dt;
}
return (clone $dt)->modify($weekday);
}
然后用法如下:
echo getPreviousWeekday($dt, 'monday')->format('l jS \of F Y h:i:s A').PHP_EOL; //Monday 22nd of July 2019 12:00:00 AM
echo getPreviousWeekday($dt, 'tuesday')->format('l jS \of F Y h:i:s A').PHP_EOL; //Tuesday 16th of July 2019 12:00:00 AM
echo getPreviousWeekday($dt, 'wednesday')->format('l jS \of F Y h:i:s A').PHP_EOL; //Wednesday 17th of July 2019 12:00:00 AM
答案 2 :(得分:0)
您可以使用strtotime
并使用last <weekday>
获得所需的内容。根据您的用例,您可以尝试以明天为起点。
$tomorrow = strtotime('tomorrow');
$monday = date('l jS of F Y h:i:s A', strtotime('last monday', $tomorrow));
$tuesday = date('l jS of F Y h:i:s A', strtotime('last tuesday', $tomorrow));
$wednesday = date('l jS of F Y h:i:s A', strtotime('last wednesday', $tomorrow));
echo $monday.PHP_EOL;
echo $tuesday.PHP_EOL;
echo $wednesday.PHP_EOL;
这将返回:
Monday 15th of July 2019 12:00:00 AM
Tuesday 16th of July 2019 12:00:00 AM
Wednesday 10th of July 2019 12:00:00 AM