提问人:maidan 提问时间:9/13/2023 最后编辑:RiggsFollymaidan 更新时间:9/14/2023 访问量:43
使用 \DateTime 获取下一个工作日(包括今天)
Using \DateTime to get next weekday including today
问:
这有点难以解释。
我有一个任务,每周触发一次。用户通过选择日期、小时和分钟来指定何时发生这种情况。
当任务被触发时,执行时间被存储(),然后一周后再次被触发。$lastDateTime
$day = 4;
$hour = 10;
$minute = 30;
$daynames = array(
0 => 'Sunday',
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
4 => 'Thursday',
5 => 'Friday',
6 => 'Saturday',
);
$now = (new \DateTime('now', new \DateTimeZone($offset)));
$last = $lastDateTime;
$next = (new \DateTime(' ' . $daynames[$day], new \DateTimeZone($offset)))
->setTime($hour, $minute, 0);
if ($now > $next) {
// trigger the task
}
问题是,如果今天是触发日,那么就是过去的一整天,因此触发是不间断的。$next
如果这样做,我无法触发当前日期:
$next = (new \DateTime('next ' . $daynames[$day], new \DateTimeZone($offset)))
->setTime($hour, $minute, 0);
答:
1赞
maidan
9/14/2023
#1
因此,@TimLewis建议是最简单和最好的解决方案。
由于我总是有一个时间戳值,所以我只是像这样使用它:lastDateTime
$now = (new \DateTime('now', new \DateTimeZone($offset)));
$next = clone $lastDateTime;
$next->modify("+7 days")->setTime($hour, $minute, 0);
if ($now > $next) {
// trigger the task
}
如果您有周以外的其他间隔,也可以非常简单地使用:
// daily
$next->modify("+1 days");
$next->setTime($hour, $minute, 0);
// hourly
$next->modify("+1 hour");
$hourWithoutMinutes = (int) ($next)->format('H');
$next->setTime($hourWithoutMinutes, $minute, 0);
// minute intervalls
$next->modify("+{$interval} minutes");
评论
\DateTime('monday')->setTime(10, 30, 0)
$last
if ($now > $next)
工作正常。但@TimLewis建议是我遵循的。它稍微改变了整个 approch,但也使它更简单,并且由于总是有一个值,因此切换到该方法时应该没有问题。last