PHP回合时间为:00或:30

I've looked at other answers on here but they don't seem to help me.

If the time is 05:30 in the database, and the current time is 05:59, I want to round it back down to 05:30 not 06:00, but once the time reaches 06:00 I want it to stay on the :00 minutes until it reaches 06:30.

Does that even make sense? It's like rounding it down half an hour sorta.

I'm trying this code I took from another website but it's only doing :00 minutes, it doesn't do :30 if it's past :30 minutes.

$hour = date('H');
$minute = (date('n')>30)?'30':'00';
$roundnow = "$hour:$minute";

Thank you.

This is quite a simple operation if you use the fact that there are 3600 seconds in an hour and 1800 in half an hour. This allows us to use the timestamp modulus 1800 to round the time as you wish.

I always use the DateTime classes when working with dates and times, so a function like this would do the job for you:-

/**
 * @param DateTime $dateTime The dateTime to be rounded
 *
 * @return DateTime The rounded DateTime
 */
function roundDateTime(\DateTime $dateTime)
{
    $rounded = clone $dateTime; //Avoid side effects
    $rounded->setTimestamp($rounded->getTimestamp() - $rounded->getTimestamp() % 1800);
    return $rounded;
}

You can see it working here with some test code to prove that it does.