php - Getting closest DateTime using strtotime formats
问题描述
DateTime accepts formats acceptable to strtotime and as such DateTime::modify('previous sunday')
and DateTime::modify('sunday next week')
will alter the DateTime object's timestamp to be the previous Sunday and next Sunday, respectively.
How does one change the timestamp to the closest Sunday? For instance, if DateTime's timestamp was currently on a Monday, it would be changed to the previous Sunday, and if it was currently on a Friday, it would be changed to the next Sunday?
解决方案
The relative time formats do not support a "closest day" (that I know of). You can compare the next and previous differences to see which is closest:
function closestWeekday(DateTimeInterface $date, int $dayOfWeek) {
if( !($date instanceof DateTimeImmutable) ) {
$date = DateTimeImmutable::createFromMutable( $date );
}
$dowStr = jddayofweek($dayOfWeek, CAL_DOW_LONG);
$prevDate = $date->modify('previous ' . $dowStr);
$nextDate = $date->modify('this ' . $dowStr);
$prevDiff = $prevDate->diff($date);
$nextDiff = $nextDate->diff($date);
return ($prevDiff->days < $nextDiff->days) ? $prevDate : $nextDate;
}
$wed = new DateTime('wednesday');
$thur = new DateTime('thursday');
// Find closest Sunday to this Wednesday
$closestDay1 = closestWeekday($wed, 6);
// Find closest Sunday to this Thursday
$closestDay2 = closestWeekday($thur, 6);
// Second argument is an integer representing the day of week you want to find
// 0 = Monday, 1 = Tuesday, 2 = Wednesday, ..., 6 = Sunday
推荐阅读
- php - 如何使用 php.ini 开启 Keep Alive
- mysql - 为什么Between找不到结束日期
- java - 使用递归查找数组是否对称
- oracle - 您如何在没有任何连接或 where 条件的情况下提高视图的性能?
- oracle - 我需要计算两个日期时间字段之间的差异,然后根据第一个计算显示一个百分比
- docker - 如何设置挂钩以在 Kubernetes pod 重启时发送电子邮件?
- reactjs - 为什么单击展开按钮会在反应中关闭侧面板?
- python - 如何使用 setuptools 为 wheel 包放置和加载预构建的本地库
- windows - 如何在 Arm64 Windows 10 机器上安装 cygwin?
- javascript - 从查询输出 JSON 数组 | 节点JS