How to Convert Minutes to Hours and Minutes in PHP?

Mary-Kate Olsen
Release: 2024-11-01 07:18:02
Original
172 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!