我正在用PHP生成一个UTC/GMT日期,该日期的格式需要为yyyyMMddHHmm
,并且需要四舍五入到最接近的分钟。
例如,January 3rd, 2020 13:28:56
需要是202001031329
,并且需要四舍五入到最接近的分钟。(30秒或更长时间向上取整,否则向下取整(
例如:
<?php
/*
Start with the UTC/GMT time -- January 3rd, 2020 13:28:56
Round to the nearest minute -- January 3rd, 2020 13:29:00
Convert to format yyyyMMddHHmm -- 202001031329
*/
$date = gmdate("YmdHi", time());
// Need to round to the nearest minute (30 seconds or greater rounds up, otherwise round down)
echo $date;
?>
到目前为止,我已经找到了如何使用gmdate()
获取当前日期并将其设置为正确的格式。然而,我不知道如何精确到最近的一分钟。
我建议您改用DateTime
对象。如果你想正确地处理日期(和时间(,可能会非常困难,PHP已经让你很容易用这种方式处理了。
然后,如果";秒针";至少为30:
$dateTime = new DateTime();
$dateTime->setTimezone(new DateTimeZone('UTC'));
echo 'Debug date: ' . $dateTime->format('Y-m-d H:i:s') . PHP_EOL;
echo 'Rounded to minute: ';
if ($dateTime->format("s") >= 30) {
$dateTime->add(new DateInterval('PT1M')); // adds one minute to current time
}
echo $dateTime->format("YmdHi") . PHP_EOL;
示例输出:
Debug date: 2021-03-18 23:57:25
Rounded to minute: 202103182357
Debug date: 2021-03-18 23:57:38
Rounded to minute: 202103182358
Debug date: 2021-03-18 23:59:34
Rounded to minute: 202103190000
这也考虑到了重叠的天数等等(见上面的最后一个例子(,而篡改原始数字不会——或者至少这样会变得非常复杂。
time((的结果将以秒为单位。如果你想四舍五入,你可以简单地增加30秒,然后按照以下格式提取相关部分:
$date = gmdate("YmdHi", time() + 30);
echo $date;