Last Updated: February 25, 2016
·
539
· bajalovic

From hours to DateInterval string

I had a time difference stored in database as hours (as float). I had to calculate that with some DateTime formats so I wrote this little function which creates a DateInterval string needed for constructing DateInterval object.

function fromHoursToDateInterval($step)
{
    $dateTimeInterval = "P";
    if ($step < 1) {
        $dateTimeInterval .= "T" . round($step * 60) . "M";
    } elseif ($step < 24) {
        $hours = floor($step);
        $minutes = round(($step - $hours) * 60);
        $hoursString = ($hours > 0) ? round($hours) . "H" : "";
        $minutesString = ($minutes > 0) ? round($minutes) . "M" : "";
        $dateTimeInterval .= "T" . $hoursString . $minutesString;
    } else {

        $days = floor($step / 24);
        $hours = round(($step - $days * 24), 2);
        $minutes = round(($hours - floor($hours)) * 60);
        $daysString = ($days > 0) ? $days . "D" : "";
        $hoursString = $hours > 0 ? round($hours) . "H" : "";
        $minutesString = $minutes > 0 ? round($minutes) . "M" : "";
        $dateTimeInterval .= $daysString . (($hours > 0 || $minutes > 0) ? "T" . $hoursString . $minutesString : "");
    }

    return $dateTimeInterval;
}

usage:

echo fromHoursToDateInterval(1.3); // output: PT1H18M
echo fromHoursToDateInterval(10.2); // output: PT10H12M
echo fromHoursToDateInterval(30.5); // output: P1DT6H30M