Question

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?

Was it helpful?

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

OTHER TIPS

The easiest way, to get ISO-8601 time interval duration, is with method createFromDateString

Use:

echo getISO8601duration_withZeros("3 year 20 day 15 minute"); # P3Y0M20DT0H15M0S
echo getISO8601duration_withZeros("1 hour 120 minutes");      # P0Y0M0DT1H120M0S
echo getISO8601duration_withZeros("7 year 5 month 3 day");    # P7Y5M3DT0H0M0S

# 13:10 example
$dt = new DateTime('13:10');
$interval_spec = "{$dt->format('H')} hour {$dt->format('i')} minute";
echo getISO8601duration_withZeros($interval_spec);            # P0Y0M0DT13H10M0S

Function:

function getISO8601duration_withZeros($interval_spec) {
    $interval = DateInterval::createFromDateString($interval_spec);
    return $interval->format('P%yY%mM%dDT%hH%iM%sS');
}

Demonstration:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top