Asked  7 Months ago    Answers:  5   Viewed   37 times

I would like to convert time strings (Such as 2:12:0) to decimal format in hours (ex 2:12:0 would be 2.2 hours) in PHP.



A fairly dumb conversion from the top of my head, using explode by colon:


$hms = "2:12:0";
$decimalHours = decimalHours($hms);

function decimalHours($time)
    $hms = explode(":", $time);
    return ($hms[0] + ($hms[1]/60) + ($hms[2]/3600));

echo $decimalHours;

Wednesday, March 31, 2021
answered 7 Months ago

You need a better math extension like BC Math, GMP... to handle the more precise precision.

Limitation of floating number & integer

Wednesday, March 31, 2021
answered 7 Months ago

You can use the DateTimeZone class:

$gmt = new DateTimeZone("GMT");
$datetimeInGMT = new DateTime($now, $gmt);

It also takes locations in the form continent/city, e.g. Europe/London.

If your datetime is non-UTC, you can use setTimezone:

$datetimeInGMT = new DateTime($now, new DateTimeZone("America/New_York"));
$datetimeInGMT->setTimezone(new DateTimeZone("GMT"));
Wednesday, March 31, 2021
answered 7 Months ago
$dt = DateTime::createFromFormat('n/d/Y', '7/03/2013');
echo $dt->format('Y-m-d H:i:s');

See it in action

The times will vary depending on when you run the code.

Saturday, May 29, 2021
answered 5 Months ago

Drop all that code, and just use 'strtol' from the standard library.

 #include <stdlib.h>
 long strtol (const char *__nptr, char **__endptr, int __base)

For your use:

long decimal_answer = strtol("0005607947", NULL, 16);
Saturday, August 7, 2021
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :