phpdateinterval

Normalize DateInterval in PHP


The situation/issue

I have an issue with DateInterval in PHP.

Given the following code

$interval = new DateInterval("PT6000S");
echo $interval->h; // 0
echo $interval->i; // 0
echo $interval->s; // 6000
echo $interval->format("%h:%i"); // 0:0

I want this to represent 1 hour and 40 minutes, not 6000 seconds.

The question

Is there a built-in way to normalize the DateInterval? A specific way of writing the duration string? Or is this something that must be done normally?

I can modify the way it's created and formated if anyone has a "work-around" to suggest.

I have done my research, but strangely enough I have not found anything helpful with this issue.


Solution

  • The DateInterval class is a bit annoying like that. Strictly it's doing the right thing, since your interval spec string specified zero minutes and hours, but it's definitely not helpful that it doesn't roll over excess seconds into minutes and hours.

    One option I've used before is to add the interval to a new DateTime object initialised to the Unix epoch, then format the resulting time instead. This would mean using the standard date format strings (so h rather than %h, etc)

    echo (new DateTime('@0'))->add(new DateInterval("PT6000S"))->format('h:i');
    // 01:40
    

    See https://3v4l.org/OX6JF