Home > Backend Development > PHP Tutorial > How do I convert minutes to hours and minutes in PHP?

How do I convert minutes to hours and minutes in PHP?

Mary-Kate Olsen
Release: 2024-11-01 02:12:02
Original
838 people have browsed it

How do I convert minutes to hours and minutes in PHP?

Convert Minutes to Hours and Minutes in PHP

Converting a number of minutes into its hour and minute representation can be useful in various scenarios. PHP provides a straightforward method to achieve this conversion. This article explores how to perform this conversion effectively using PHP, utilizing the convertToHoursMins() function.

Problem Statement

Consider a PHP variable $final_time_saving that contains the number of minutes, e.g., 250. The goal is to convert this value into a string representation in the format "4 hours 17 minutes".

Solution Using convertToHoursMins() Function

The convertToHoursMins() function takes the number of minutes as an argument and an optional format string to control the output format. Here's the code:

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

// Example usage
echo convertToHoursMins(250, '%02d hours %02d minutes'); // Output: 4 hours 10 minutes</code>
Copy after login

In this example, we pass the number of minutes (250) and a custom format string (d hours d minutes) that specifies the desired output format. The function converts the minutes into 4 hours and 10 minutes and returns the formatted string.

The above is the detailed content of How do I 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