2

I have a string in the format of hh:mm:ss that I convert to an integer representing the total number of seconds. For example:

01:43:03

01 * 3600
43 * 60
03 * 1

The above example results in an integer value of 6183.

After performing some logic using this value I then need to convert the integer back to a strict format of hh:mm:ss.

Note that this isn't a time of day. It is an amount of time. Like, I spent 1 hour, 43 minutes and 3 seconds driving from one point to another.

What is the shortest way of coding this conversion so that 6183 seconds is formatted as 01:43:03 ?

rwkiii
  • 5,716
  • 18
  • 65
  • 114
  • 1
    http://stackoverflow.com/questions/3172332/convert-seconds-to-hourminutesecond – Jhorra Feb 18 '17 at 06:22
  • 2
    Possible duplicate of [Convert seconds to Hour:Minute:Second](http://stackoverflow.com/questions/3172332/convert-seconds-to-hourminutesecond) – l'L'l Feb 18 '17 at 06:23
  • Possible duplicate comments. +1 for both though. I honestly searched but didn't find this example. It's exactly what I needed. – rwkiii Feb 18 '17 at 06:27
  • 1
    The duplicate isn't a good choice. If you go over 24 hours it'll just cycle right back around to zero, at least not the accepted answer the 2nd answer is better. – Jonathan Feb 18 '17 at 06:32
  • @Augwa It's better, but the second answer doesn't format with leading zeros. Still, that post gave me what I needed. – rwkiii Feb 18 '17 at 07:11
  • 2
    make use of the `str_pad()` function to add your leading zero's. – Jonathan Feb 18 '17 at 07:12

2 Answers2

2

Use this-

echo $time = date("h:i:s A T",'6183');

I think it will help.

John Ambrose
  • 167
  • 1
  • 11
1

You can simply use like this

<?php
    $total_seconds = 160183;
    $seconds = intval($total_seconds%60);
    $total_minutes = intval($total_seconds/60);
    $minutes = $total_minutes%60;
    $hours = intval($total_minutes/60);
    echo "$hours:$minutes:$seconds";
?>

Check live demo : http://sandbox.onlinephpfunctions.com/code/78772e1462879ce3a20548a3a780df5de4e16e2c

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109