Search code examples
phpmysqltimeepoch

Converting Epoch time to an H:mm timestamp in PHP


This seems like there should be a very easy solution, however everything I'm trying is either giving me an error or the wrong result.

I'm pulling data from a MySQL table and the time is stored in the Epoch format in the database. When I make the query on the website it's showing: 3672 (the same number shown in the database). I've tried using the date() function, a number of different str* functions, different arithmetic operations, however nothing is giving me the actual time, which should be showing as: '1:02'.

I'm not trying to pull the date, actual time, etc. I'm just trying to convert an Epoch time string to a traditional 'H:mm' format, because these are for durations, not timestamps.

Any help would be greatly appreciated!


Solution

  • As others already noticed, this is not really any standard epoch time but simply number of seconds since midnight.

    Looking at your example, you only need hours and minutes (rounded up). This will give you those:

    $h = (int)($number / 3600);
    $m = ceil(($number - $h * 3600) / 60);
    $result = sprintf('%d:%02d', $h, $m);
    

    Dividing number by 3600 (60 for seconds * 60 for minutes) will give you number of hours. Using your example of 3672 this will give you 1.

    To get minutes you just remove hours to get seconds (72) and then divide that by 60 to get minutes (1 minutes and 12 seconds). Since your example specifies 1:02 is result, you can simply take next upper integer (2).

    At end result is 1:02, as you specified.