简体   繁体   中英

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.

For example, January 3rd, 2020 13:28:56 needs to be 202001031329 and it needs to be rounded to the nearest minute. (30 seconds or greater rounds up, otherwise round down)

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. However, I'm not sure how to round to the nearest minute.

I suggest you use a DateTime object instead. 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.

Then, just add one minute if the "seconds hand" is at least at 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. If you want to round up, you could simply add 30 seconds to it, then take the relevant parts in the format:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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