PHP convert string time to second

Viewed 56

In our mikrotik when we get user uptime, that's return a string such as "2d13m30s" and i should convert it to second, this stirng can be "13m30s" or "30s", i tired to convert it to second but i think there isn't standard php for that

i think in php this function as strtotime can't be help me to convert it to second and this code what i tested and gmdate can convert second to time:

date("s",strtotime("2h2m30s"))
3 Answers

strtotime understands relative dates, but its units are a bit more verbose than just single letters. Simply replace like so:

$strtotime_input = strtr('5d3h20s', [
  'w' => ' week ',
  'd' => ' day ', 
  'h' => ' hour ', 
  'm' => ' minute ', 
  's' => ' second '
]) . ' ago';

Now strings such as 5d3h20s will turn into 5 day 3 hour 20 second ago. Feed that into strtotime():

$timestamp = strtotime($strtotime_input);
echo date('Y-m-d H:i:s', $timestamp);

// Or if you need the number of seconds:

echo time() - $timestamp;

I see as per the question tags that you have Carbon installed so CarbonInterval already handles that for you:

echo \Carbon\CarbonInterval::fromstring('2h2m30s') . "\n";
echo \Carbon\CarbonInterval::fromstring('2h2m30s')->totalSeconds . "\n";

Output:

2 hours 2 minutes 30 seconds
7350

You can parse it with Regex, too:

/(?:(?<days>\d+)d)?(?:(?<minutes>\d+)m)?(?:(?<seconds>\d+)s)/1

$interval = '987d6m5s';
preg_match('/(?:(?<days>\d+)d)?(?:(?<minutes>\d+)m)?(?:(?<seconds>\d+)s)/', $interval, $matches);

$days = $matches['days'] ?: 0;
$minutes = $matches['mins'] ?: 0;
$seconds = $matches['seconds'] ?: 0;

$intervalInSeconds = $days * 24 + $mins * 60 + $seconds; 

Live example

Any date and similar functions does not work nicely with interval of seconds and not timestamp of seconds.

Related