简体   繁体   English

PHP 获取 UTC/GMT 时间,四舍五入到最接近的分钟,格式为 yyyyMMddHHmm

[英]PHP get UTC/GMT time, round to nearest minute, and format to yyyyMMddHHmm

I'm generating a UTC/GMT date with PHP that needs to be in the format yyyyMMddHHmm and needs to be rounded to the nearest minute.我正在使用 PHP 生成 UTC/GMT 日期,该日期需要采用yyyyMMddHHmm格式,并且需要四舍五入到最接近的分钟。

For example, January 3rd, 2020 13:28:56 needs to be 202001031329 and it needs to be rounded to the nearest minute.例如January 3rd, 2020 13:28:56需要为202001031329并且需要四舍五入到最接近的分钟。 (30 seconds or greater rounds up, otherwise round down) (30 秒或更长时间向上取整,否则向下取整)

For example:例如:

<?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;
?>

So far I've figured out how to get the current date with the gmdate() and put it in the right format.到目前为止,我已经弄清楚如何使用gmdate()获取当前日期并将其以正确的格式放置。 However, I'm not sure how to round to the nearest minute.但是,我不确定如何四舍五入到最近的分钟。

I suggest you use a DateTime object instead.我建议您改用DateTime object Handling dates (and times) can be very difficult if you want to do it correctly, and PHP already makes it pretty easy for you this way.如果您想正确处理日期(和时间),可能会非常困难,而 PHP 已经让您通过这种方式变得非常容易。

Then, just add one minute if the "seconds hand" is at least at 30:然后,如果“秒针”至少为 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;

Example outputs:示例输出:

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

This also takes care of overlapping days and such (see last example above), which fiddling around with the raw numbers would not - or at least it would get very complicated that way.这也处理了重叠的日子等(见上面的最后一个例子),摆弄原始数字不会 - 或者至少那样会变得非常复杂。

The result of time() will be in seconds. time() 的结果将以秒为单位。 If you want to round up, you could simply add 30 seconds to it, then take the relevant parts in the format:如果你想四舍五入,你可以简单地增加 30 秒,然后采用以下格式获取相关部分:

$date = gmdate("YmdHi", time() + 30);
echo $date;

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

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