问题描述
我正在使用的图书馆和网络服务,在ISO 8601:PnYnMnDTnHnMnS中传达时间间隔。我想将这样的格式转换成秒。反之亦然。秒数更容易计算。示例间隔值为:
- PT1M或PT60S(1分钟)
- PT1H,PT60M或PT3600S(1小时)
我需要两个功能:从这些值解析为秒: iso8601_interval_to_seconds()
,从秒到这样的间隔: iso8601_interval_from_seconds()
。
后者相当简单,因为它可以做为PT {$ seconds} S,只是随着秒数传递。也许这可以更好的解析器切换到H(小时)或M(分钟)?
第一个更难,但也许PHP中有许多字符串转换器之一呢?我很乐意学习如何使用这样的函数来解析间隔。或者学习一个选择。
看起来像PHP 5.3的支持这一点。
如果您不能使用5.3,我认为任何这样的转换功能将知道一年,一个月,一天,一小时和一个小时内有多少秒分钟。然后,当从秒转换时,它将以该顺序分割,每次以前一次操作的模数,直到只剩下
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: iso8601_interval_to_seconds()
and from seconds into such intervals: iso8601_interval_from_seconds()
.
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.
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.
这篇关于解析并创建ISO 8601日期和时间间隔,如PHP中的PT15M的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!