berkes berkes - 5 months ago 24
PHP Question

Parse and create ISO 8601 Date and time intervals, like PT15M in PHP

A library and webservice I am using, communicates time-intervals in ISO 8601: PnYnMnDTnHnMnS. I want to convert such formats to seconds. And vice versa. Seconds are a lot easier to calculate with.

Example interval values are:

  • PT1M or PT60S (1 minute)

  • PT1H, PT60M or PT3600S (1 hour)

I need two functions: parse from such values to seconds:
and from seconds into such intervals:

The latter is rather simple, because it could be done as `"PT{$seconds}S", just pass seconds along, at all times. Maybe this can be done nicer with a parser that switches to H(hour) or M(minute)?

The first is harder, but maybe there is a trick with one of the many string-to-date converters in PHP? I would love to learn how to use such a function for parsing intervals. Or learn an alternative.

Answer Source

It looks like PHP 5.3's DateInterval supports this.

If you can't use 5.3, I suppose any such conversion function would know how many seconds are in a year, a month, a day, an hour, and a minute. Then, when converting from seconds, it would divide in that order, each time taking the modulo of the previous operation, until only <60 seconds are left. When converting from an ISO 8601 interval representation it should be trivial to parse the string and multiply each found element accordingly.