How to create a DateInterval from a time string

If I have a time format string, for example "14:30:00" ("hours: minutes: seconds"), how can I get DateInterval from a string?

I can get DateTime:

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

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

+4
source share
1 answer

If you need an interval of 14 hours and 30 minutes, just use the constructor ...

$interval = new DateInterval('PT14H30M');

To break it ...

  • P- All interval lines must begin with P(for a period). We do not use period intervals, although so on ...
  • T - Time specification starts
  • 14H - 14 hours
  • 30M - 30 minutes

14:30:00, sscanf ...

list($hours, $minutes, $seconds) = sscanf('14:30:00', '%d:%d:%d');
$interval = new DateInterval(sprintf('PT%dH%dM%dS', $hours, $minutes, $seconds));
+14

Source: https://habr.com/ru/post/1526646/


All Articles