How to create a DateInterval from a time string

不打扰是莪最后的温柔 提交于 2019-12-01 17:11:44

问题


If I have a time format string like "14:30:00" ("hours:minutes:seconds"), how do I get a DateInterval from the string?

I can get a DateTime:

$datetime= DateTime::createFromFormat("H:i:s","14:30:00");

But I need to add it to another DateTime object, and date_add needs a DateInterval.


回答1:


If you want an interval that is 14 hours and 30 minutes, simply use the constructor...

$interval = new DateInterval('PT14H30M');

To break it down...

  • P - all interval spec strings must start with P (for Period). We aren't using any period intervals though so on to...
  • T - this starts the Time spec
  • 14H - 14 hours
  • 30M - 30 minutes

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));


来源:https://stackoverflow.com/questions/21742329/how-to-create-a-dateinterval-from-a-time-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!