83

I have a variable called $final_time_saving which is just a number of minutes, 250 for example.

How can I convert that number of minutes into hours and minutes using PHP in this format:

4 hours 10 minutes

Rob
  • 6,304
  • 24
  • 83
  • 189

14 Answers14

157
<?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'); // should output 4 hours 17 minutes
Martin Bean
  • 38,379
  • 25
  • 128
  • 201
124
echo date('H:i', mktime(0,257));
Alastair
  • 6,837
  • 4
  • 35
  • 29
  • 3
    best sollution! also, for seconds => date('H\hi\m:s\s', mktime(0,0,$totalSeconds)) – mwm Apr 02 '14 at 16:50
  • 22
    Wrong solution. Doesn't work for times > 24 hours and also depends on timezone configuration. It's not a *date* you're working with, don't use `date` functions. – deceze Jul 16 '14 at 09:56
  • It is a solution to the _question_ but you're correct, @deceze , it isn't accurate with periods longer than 24h. I don't see how this is timezone-dependant, though. Rather; `gmmktime` would return a locally-offset time. – Alastair Jul 21 '14 at 15:43
  • Admittedly, if you write code exactly like this, timezones probably won't affect it. However, it's easy to introduce bugs due to timezone shenanigans: http://3v4l.org/oH4ao – deceze Jul 21 '14 at 15:47
  • 5
    Perfect when you just need to convert some integers and you stay within the 24 hour boundary! – Daan Oct 03 '14 at 08:14
  • How can I make this work with seconds? I tried following date('H:i:s').. but that did not work any idea? – utdev Feb 01 '17 at 10:36
  • 6
    It's a misleading solution, should at least be noted that this doesn't work for > 24 hours. – Tool Jan 04 '19 at 17:27
  • Yep this bit me in the butt when we had a time > 24 hours. Dont use this. – M H Oct 11 '21 at 18:49
50
$hours = floor($final_time_saving / 60);
$minutes = $final_time_saving % 60;
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
13

You can achieve this with DateTime extension, which will also work for number of minutes that is larger than one day (>= 1440):

$minutes = 250;
$zero    = new DateTime('@0');
$offset  = new DateTime('@' . $minutes * 60);
$diff    = $zero->diff($offset);
echo $diff->format('%a Days, %h Hours, %i Minutes');

demo

Glavić
  • 42,781
  • 13
  • 77
  • 107
  • This breaks if you have minutes as something like `12.99` – Ray Feb 20 '19 at 16:09
  • 2
    Decimal is not a valid minute format. The question is "Convert number of minutes into hours & minutes using PHP". – M H Oct 11 '21 at 18:52
9

@Martin Bean's answer is perfectly correct but in my point of view it needs some refactoring to fit what a regular user would expect from a website (web system).
I think that when minutes are below 10 a leading zero must be added.
ex: 10:01, not 10:1

I changed code to accept $time = 0 since 0:00 is better than 24:00.

One more thing - there is no case when $time is bigger than 1439 - which is 23:59 and next value is simply 0:00.

function convertToHoursMins($time, $format = '%d:%s') {
    settype($time, 'integer');
    if ($time < 0 || $time >= 1440) {
        return;
    }
    $hours = floor($time/60);
    $minutes = $time%60;
    if ($minutes < 10) {
        $minutes = '0' . $minutes;
    }
    return sprintf($format, $hours, $minutes);
}
Mihail Velikov
  • 566
  • 1
  • 8
  • 14
  • 3
    Good point, I agree the minutes need a leading zero. Another way you could do it would be to use the padding functionality of sprintf: `echo sprintf('%02d', 2); // this echos "02"` – Dave Hollingworth Apr 17 '13 at 13:00
  • same as minutes, i added it for hours, specially important when adding to database so mysql won't get confused – Dvid Silva Jun 24 '13 at 17:12
  • the return value it's not consistent, may return void, may return string – Erlang Parasu Nov 15 '19 at 05:14
8
$t = 250;
$h = floor($t/60) ? floor($t/60) .' hours' : '';
$m = $t%60 ? $t%60 .' minutes' : '';
echo $h && $m ? $h.' and '.$m : $h.$m;

4 hours and 10 minutes

Mike
  • 247
  • 2
  • 5
  • 10
5

Sorry for bringing up an old topic, but I used some code from one of these answers a lot, and today I told myself I could do it without stealing someone's code. I was surprised how easy it was. What I wanted is 510 minutes to be return as 08:30, so this is what the code does.

function tm($nm, $lZ = true){ //tm = to military (time), lZ = leading zero (if true it returns 510 as 08:30, if false 8:30
  $mins = $nm % 60;
  if($mins == 0)    $mins = "0$mins"; //adds a zero, so it doesn't return 08:0, but 08:00

  $hour = floor($nm / 60);

  if($lZ){
    if($hour < 10) return "0$hour:$mins";
  }

  return "$hour:$mins";
}

I use short variable names because I'm going to use the function a lot, and I'm lazy.

Lurvik
  • 51
  • 1
  • 2
4

The easiest way is :

    gmdate('H:i', $numberOfSeconds * 60)
Seif.ben
  • 62
  • 1
  • 4
3

Just in case you want to something like:

echo date('G \h\o\u\r\s i \m\i\n\u\t\e\s', mktime(0, 90)); //will return 1 hours 30 minutes
echo date('G \j\a\m i \m\e\n\i\t', mktime(0, 90)); //will return 1 jam 30 menit
kelaskakap
  • 113
  • 2
  • 11
1
function hour_min($minutes){// Total
   if($minutes <= 0) return '00 Hours 00 Minutes';
else    
   return sprintf("%02d",floor($minutes / 60)).' Hours '.sprintf("%02d",str_pad(($minutes % 60), 2, "0", STR_PAD_LEFT)). " Minutes";
}
echo hour_min(250); //Function Call will return value : 04 Hours 10 Minutes
HIR
  • 192
  • 3
  • 11
1
$m = 250;

$extraIntH = intval($m/60);

$extraIntHs = ($m/60);             // float value   

$whole = floor($extraIntHs);      //  return int value 1

$fraction = $extraIntHs - $whole; // Total - int = . decimal value

$extraIntHss =  ($fraction*60); 

$TotalHoursAndMinutesString  =  $extraIntH."h ".$extraIntHss."m";
Omprakash Patel
  • 532
  • 4
  • 15
1

Thanks to @Martin_Bean and @Mihail Velikov answers. I just took their answer snippet and added some modifications to check,

  1. If only Hours only available and minutes value empty, then it will display only hours.

  2. Same if only Minutes only available and hours value empty, then it will display only minutes.

  3. If minutes = 60, then it will display as 1 hour. Same if minute = 1, the output will be 1 minute.

Changes and edits are welcomed. Thanks. Here is the code.

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

        
            if($minutes == 0){

                if($hours == 1){

                    $output_format = '%02d hour ';

                }else{

                    $output_format = '%02d hours ';
                }

                
                $hoursToMinutes = sprintf($output_format, $hours);

            }else if($hours == 0){

                if ($minutes < 10) {
                        $minutes = '0' . $minutes;
                }

                if($minutes == 1){

                    $output_format  = ' %02d minute ';

                }else{

                    $output_format  = ' %02d minutes ';
                }
                
                $hoursToMinutes = sprintf($output_format,  $minutes);

            }else {

                if($hours == 1){

                    $output_format = '%02d hour %02d minutes';

                }else{

                    $output_format = '%02d hours %02d minutes';
                }
                
                $hoursToMinutes = sprintf($output_format, $hours, $minutes);
            }
            
            return $hoursToMinutes;
        }
olibiaz
  • 2,551
  • 4
  • 29
  • 31
Rams
  • 41
  • 7
0

2022 answer using Carbon

Carbon::createFromTime(
intdiv($final_time_saving, 60), 
($final_time_saving % 60), 
0, 
0)
->format('H:i')
pippoBoy
  • 11
  • 2
  • Please don't post code-only answers but add a little textual explanation about how and why your approach works and what makes it different from the other answers given. You may also have a look at our ["How to write a good answer"](https://stackoverflow.com/help/how-to-answer) entry. – ahuemmer Aug 01 '22 at 06:55
-1

check this link for better solution. Click here

How to convert hh:mm:ss to minutes

$minutes=$item['time_diff'];
$hours =   sprintf('%02d',intdiv($minutes, 60)) .':'. ( sprintf('%02d',$minutes % 60));
Community
  • 1
  • 1
pankaj
  • 1
  • 17
  • 36