Search code examples
phpdatetimerounding

Round up time to 1 hour if it's longer than 45 minutes in PHP


Basically i need if it's more than or equal to 45 minutes, it must be rounded up. if it's less than that, it must be rounded down

Example :

- 18:12 needs to be 18:00
- 18:32 needs to be 18:00
- 18:45 needs to be 19:00
- 18:52 needs to be 19:00
- etc.

I'm not sure if that's possible. really need your help, thanks


Solution

  • The best solution is probably using the Date function PHP has.

    if((int)date('i', strtotime('18:46')) >= 45){
        echo date('H:00', strtotime('+ 1 hour', strtotime('18:46')));
    } else {
        echo '18:46';
    }
    

    Also could be achieved with string functions but then you'll need to account for midnight notations.

    An explode approach could start with:

    list($hours, $minutes) = explode(':', '18:46');
    

    A regex approach could start with:

    (?:[01]\d|2[0-3]):(4[5-9]|5\d)