Question

i want to get the total amount of hours that is outputted from our database, but the problem is the values are on string format

ex of the values:

9H:20M
3H:13M
3H:50M
6H:30M

TOTAL:22H:53M

i want to get the total of all the values and display it afterwards, but i don't know how to segregate the numbers from the string and then convert it to time format, is there any way for me to achieve the result i'm looking for using a php script for conversion and segregation of values and data?

Was it helpful?

Solution 2

You can use strtotime or the newer DateTime class, but your current format is not compatible, so you have to some modification before. This is a possible solution:

<?php
$result = 0;
$times = array('9H:20M','3H:13M','3H:50M','6H:30M');
foreach($times as $time) {
    preg_match('/^(\d{1,2})H[:]([0-5][0-9])M$/',$time, $m);
    $timestamp = strtotime($m[1].':'.$m[2]);
    $result+=$timestamp;
}
echo date('H:i',$result);
?>

I think the better approach for this is, to grep the total time directly from DB.

OTHER TIPS

Here is a pretty basic solution:

<?php

$times = array("9H:20M", "3H:13M", "3H:50M", "6H:30M",);

$total = 0;
foreach ($times as $time) {
  preg_match("#(\d+)H:(\d+)M#", $time, $matches);
  $total += 60 * $matches[1] + $mtaches[2];
}

echo $total;

This creates a value $total which contains the total number of minutes. Now you can convert back to H and M.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top