Search code examples
phpstringtimeintervalsperiod

PHP convert time into a Time Period


There appears to be a lot of info converting a time period into a time, but not the other way around.

An example of what I need to do, is convert say 120 minutes into P0DT2H0M0S. And 13:10 into P0DT13H10M0S. And 120 minutes into PT2H0M0S.

Any quick and easy way to do this?


Solution

  • I believe the format you're describing is the ISO 8601 date/time format. Here's how it describes intervals.

    In the PHP documentation for the DateInterval class, someone has shared an example of how you might convert a string into ISO 8601 in an object-oriented way:

    http://www.php.net/manual/en/class.dateinterval.php#113415

    And here is someone else's solution, using functional rather than object-oriented date methods:

    https://stackoverflow.com/a/13301472/2119660