如何从时间字符串创建DateInterval [英] How to create a DateInterval from a time string
本文介绍了如何从时间字符串创建DateInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个类似 14:30:00的时间格式字符串( hours:minutes:seconds),如何从字符串中获取DateInterval?
If I have a time format string like "14:30:00" ("hours:minutes:seconds"), how do I get a DateInterval from the string?
我可以得到一个DateTime:
I can get a DateTime:
$datetime= DateTime::createFromFormat("H:i:s","14:30:00");
但是我需要将其添加到另一个DateTime对象中,并且date_add需要一个DateInterval。
But I need to add it to another DateTime object, and date_add needs a DateInterval.
推荐答案
如果要间隔14小时30分钟,只需使用构造函数即可。
If you want an interval that is 14 hours and 30 minutes, simply use the constructor...
$interval = new DateInterval('PT14H30M');
要分解...
-
P
-所有间隔规范字符串必须以P
开头(对于期间)。 -
T
-这将开始 Time em> spec -
14H
-14小时 -
3000万
-30分钟
P
- all interval spec strings must start withP
(for Period). We aren't using any period intervals though so on to...T
- this starts the Time spec14H
- 14 hours30M
- 30 minutes
如果必须,请使用字符串 14: 30:00 ,我会用 sscanf
进行解析,然后使用这些部分...
If you must use the string 14:30:00, I'd parse it with sscanf
and use the parts...
list($hours, $minutes, $seconds) = sscanf('14:30:00', '%d:%d:%d');
$interval = new DateInterval(sprintf('PT%dH%dM%dS', $hours, $minutes, $seconds));
这篇关于如何从时间字符串创建DateInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文