Rover P5
Rover P5

Reputation: 1

How to convert MySQL Time to ISO 8601 Duration with PHP

I have a MySQL table storing time durations in the format HH:MM:SS

I would like to convert these MySQL time entries into ISO 8601 time durations using PHP.

So for example, I would like to convert an entry in the database of 00:01:23 to be output as PT1M23S

And in cases where the duration is in hours an entry such as 01:23:04 would be output as PT1H23M4S

Any help much appreciated!

Upvotes: 0

Views: 566

Answers (2)

Niklesh Raut
Niklesh Raut

Reputation: 34914

You can do like this

 <?php 
   $time = "1:23:4";
   $converted = date('\P\TH\Hi\Ms\S', strtotime ($time));
   $converted = str_replace (['00H','00M','00H','0'],'',     $converted);
   echo $converted;
 ?>

Demo : https://eval.in/730495

Upvotes: 1

A C
A C

Reputation: 705

There are a ton of ways to approach this, but a simple (and hopefully readable) approach would be something like:

 function hmsTo8601($hmsTime)
 {
      $ret = "PT";
      $arr = array_reverse(explode(':',$hmsTime));
      $ct = count($arr);
      if ($ct >= 3) $ret.=$arr[2].'H';
      if ($ct >= 2) $ret.=$arr[1].'M';
      if ($ct >= 1) $ret.=$arr[0].'S';
      return $ret;
 }

...of course you'll want to add some error checking in a production environment, and this assumes that your table maxes out with hours.

Upvotes: 0

Related Questions