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.

 Answers

55

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

<?php 

$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
 
EnTee
answered 7 Months ago
11

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
 
lewiguez
answered 7 Months ago
93

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
 
altermativ
answered 7 Months ago
30
$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
 
freeMagee
answered 5 Months ago
63

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
 
Chvanikoff
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 :