1

I've a table with the following time format "1h1m1s" (or "1m1s"). So the question is how to convert it to seconds only format? For example 1m1s = 61 (seconds).

Tried to select from database and replace with an arithmetical operators in PHP, but it doesn't work.

$options = get_table($table_name, $order);
for($i = 0; $i < count($options); $i++){
    $duration = $options[$i]['duration'];

    $original = array("h", "m", "s");
    $change   = array('*3600+', '*60+', '*1');

    $string = str_replace($original, $change, $duration);
    echo $string;

}
Phil
  • 157,677
  • 23
  • 242
  • 245
Tim Sadvak
  • 101
  • 12

1 Answers1

2

Your "1h1m1s" format looks pretty compatible with PHP's DateInterval class. You could construct one and then use this answer to calculate the seconds.

For example, you just need to uppercase the letters in "1h1m1s", then prefix it with "PT" to make it an interval spec.

/**
 * From https://stackoverflow.com/a/25149337/283366, please upvote it
 * @param DateInterval $dateInterval
 * @return int seconds
 */
function dateIntervalToSeconds($dateInterval)
{
    $reference = new DateTimeImmutable;
    $endTime = $reference->add($dateInterval);

    return $endTime->getTimestamp() - $reference->getTimestamp();
}

$interval = new DateInterval('PT' . strtoupper($duration));
$seconds = dateIntervalToSeconds($interval);

Demo ~ https://3v4l.org/UaEYB

Phil
  • 157,677
  • 23
  • 242
  • 245
  • 1
    @TimSadvak you're welcome. Don't forget to upvote the main part of this answer over here ~ https://stackoverflow.com/a/25149337/283366 – Phil Aug 07 '18 at 05:25