Home  >  Article  >  Backend Development  >  How to Convert Minutes to Hours and Minutes in PHP?

How to Convert Minutes to Hours and Minutes in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 07:18:02172browse

How to Convert Minutes to Hours and Minutes in PHP?

Converting Minutes to Hours and Minutes in PHP

Often, you may encounter situations where you have a value representing the duration in minutes, and you need to convert it into a more human-readable format such as hours and minutes. In PHP, this conversion can be easily achieved.

To convert the minutes into hours and minutes, we can utilize the modulo arithmetic. By dividing the number of minutes by 60, we obtain the number of hours. The remainder represents the number of minutes.

<code class="php">function convertToHoursMins($time, $format = '%02d:%02d')
{
    if ($time < 1) {
        return;
    }

    $hours = floor($time / 60);
    $minutes = $time % 60;

    return sprintf($format, $hours, $minutes);
}</code>

To use this function, simply provide the number of minutes as the input argument. The function will return a string in the specified format, which defaults to two-digit hours and two-digit minutes.

For example, to convert 250 minutes into hours and minutes:

<code class="php">echo convertToHoursMins(250, '%02d hours %02d minutes');</code>

This would output "4 hours 10 minutes".

The above is the detailed content of How to Convert Minutes to Hours and Minutes in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn