33 Votes

PHP: Convert Minutes to Hours and Minutes (0:00)

Question by Guest | Last update on 2024-01-14 | Created on 2014-10-01

In one of my PHP scripts, I have a time value specified in minutes. Now, I would like to display this value on my website in the form hours:minutes. So, for example, "1:37 hours" instead of "97 minutes".

That means, I need some function that can transform the minute value into the format h:min. Is there a function available in PHP for such a conversion? Preferably, as simple as possible.

ReplyPositiveNegativeDateVotes
5Best Answer9 Votes

You could use a combination of the PHP functions date() and mktime() for that conversion.

For example, in this way:

echo date('G:i', mktime(0, 97)); // 1:37
echo date('H:i', mktime(0, 97)); // 01:37

As a first parameter, mktime() takes the number of hours, as a second (optional) parameter the minutes; after that seconds, months, days and years.

When calling mktime() with mktime(0, 97), this corresponds to 0 hours and 97 minutes, which can be outputted in a custom format using date(). With using the format-string "G:i" you will get "1:37", with "H:i" "01:37", as an example.

Of course, you can also pass the number of seconds [mktime(0, 0, 120) = 120 seconds] or you can mix the arguments [mktime(1, 2, 3) = 1 hour, 2 minutes and 3 seconds]. Likewise, you can also use all of the other characters in your format string (for example "s" for seconds with leading zeros etc).
Last update on 2024-01-14 | Created on 2014-10-01

ReplyPositive Negative
1010 Votes

Alternatively, you can also use the function sprintf() to get the same result.

Here is an example:

$t = 97;
echo sprintf("%d:%02d",   floor($t/60), $t%60);  // 1:37
echo sprintf("%02d:%02d", floor($t/60), $t%60);  // 01:37

We pass to this function the format string as well as the values that should be replaced in the string.

In the format strings we use %d for simple integer values and %02d for integer values that are to be output with two digits using leading zeros here.

As values, we are passing floor($t/60) and $t%60. With dividing by 60 and cutting the decimal places, we get the number of hours. Accordingly, we are extracting the division remainder by calculating $t%60 in order to get the number of minutes with this.
Last update on 2024-01-14 | Created on 2014-10-01

ReplyPositive Negative
Reply

Related Topics

PHP: Current Date and Time

Tutorial | 0 Comments

PHP: Upload of large Files

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.