java iso8601 PT1M,解析并创建ISO 8601日期和时间间隔,如PHP中的PT15M

这篇博客讨论了如何在PHP中将ISO8601时间间隔格式(如PT1M,PT1H)转换为秒数,以及将秒数转换回这种格式。作者提出了需要两个函数:`iso8601_interval_to_seconds()`用于解析间隔到秒,而`iso8601_interval_from_seconds()`用于从秒数构建间隔。虽然后者相对简单,只需直接拼接秒数,但前者更复杂。解决方案建议使用PHP5.3的DateInterval支持,或者通过了解一年、月、日、小时和分钟的秒数来手动转换,并在转换过程中进行除法和取模操作。对于解析ISO8601字符串,可以解析并相应地乘以元素的秒数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值