Get duration from timestamps?

Viewed 38

How can I get the following timestamps to show up as durations using PHP?

"00:00:00" should result in `0:00`
"00:00:02" should result in `0:02`
"00:00:30" should result in `0:30`
"00:02:30" should result in `2:30`
"00:20:00" should result in `20:00`
"01:02:30" should result in `1:02:30`
"10:20:03" should result in `10:20:03`
1 Answers

A regex will do what you want, assuming you're starting with strings:

The Regex ([1-9].*|.{4}$) looks for the first non-zero digit and returns it and everything after it, but in any case returns the last four characters.

<?php

$arr = ["00:00:00",
"00:00:02",
"00:00:30",
"00:02:30",
"00:20:00",
"01:02:30",
"10:20:03"];

foreach ($arr as $time) {
    preg_match('/([1-9].*|.{4}$)/', $time, $matches);
    echo $time." -> ".$matches[1]."\n";
}

Output:

00:00:00 -> 0:00
00:00:02 -> 0:02
00:00:30 -> 0:30
00:02:30 -> 2:30
00:20:00 -> 20:00
01:02:30 -> 1:02:30
10:20:03 -> 10:20:03

Demo: https://3v4l.org/eC8BQ

Related