How to Convert Minutes into Hours and Minutes in PHP?

Linda Hamilton
Release: 2024-11-01 03:22:02
Original
1080 people have browsed it

How to Convert Minutes into Hours and Minutes in PHP?

Convert Minutes into Hours and Minutes with Precision in PHP

In PHP programming, when working with time intervals, it often becomes necessary to convert a number of minutes into a user-friendly format that displays hours and minutes separately. This allows for a more intuitive understanding of time duration.

Problem:

Suppose you have a PHP variable, let's call it $final_time_saving, which represents a number of minutes, such as 250. The challenge is to convert this numerical duration into a human-readable format like "4 hours 10 minutes."

Solution:

To achieve this conversion, PHP offers a simple and efficient solution:

<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);
}

echo convertToHoursMins(250, '%02d hours %02d minutes'); // outputs "4 hours 10 minutes"</code>
Copy after login

Explanation:

  • The convertToHoursMins() function takes two parameters: $time, which is the number of minutes to be converted, and $format, which specifies the output format.
  • It first checks if the input time is valid ($time < 1) before proceeding.
  • Next, it calculates the number of hours using floor division (floor($time / 60)), which rounds down to the nearest whole number.
  • The number of minutes is then calculated using the modulo operator ($time % 60), which gives the remainder after dividing by 60.
  • Finally, the computed hours and minutes are formatted using sprintf() according to the specified $format. By default, it formats them as two-digit numbers separated by a colon ('d:d').

Example Output:

When you call the above function with $final_time_saving = 250, it will output "4 hours 10 minutes."

The above is the detailed content of How to Convert Minutes into 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