DateInterval format as ISO8601

I am currently working on a php project and should format DateInterval as ISO8601 (something like this):

P5D

You can use this format to create DateTime and DateInterval objects, but I cannot determine how to format DateInterval into this format. Whether there is a? If not, what could be an easy solution for this?

+4
source share
2 answers

Well, if you look at the specification for the format when creating it:

Y years

M months

D days

W weeks. They are converted to days, so they cannot be combined with D.

H hours

M minutes

S seconds

, (http://php.net/manual/en/dateinterval.format.php), , :

$dateInterval = new DateInterval( /* whatever */ );
$format = $dateInterval->format("P%yY%mM%dD%hH%iM%sS");
//P0Y0M5D0H0M0S
//now, we need to remove anything that is a zero, but make sure to not remove
//something like 10D or 20D
$format = str_replace(["M0S", "H0M", "D0H", "M0D", "Y0M", "P0Y"], ["M", "H", "D", "M", "Y0M", "P"], $format);
echo $format;
//P0M5D

, , -, , 0. , minutes months M - , , , , . , , P PT, , a M Minute.

:

// For 3 Months
new DateInterval("P3M");
// For 3 Minutes
new DateInterval("PT3M"));

:

// For 3 Months
new DateInterval("P3M");
// For 3 Minutes
new DateInterval("P0M3M"));
+2

@dave, , , . ISO-8601, , T , . , :

function date_interval_iso_format(DateInterval $interval) {
    list($date,$time) = explode("T",$interval->format("P%yY%mM%dDT%hH%iM%sS"));
    // now, we need to remove anything that is a zero, but make sure to not remove
    // something like 10D or 20D
    $res =
        str_replace([ 'M0D', 'Y0M', 'P0Y' ], [ 'M', 'Y', 'P' ], $date) .
        rtrim(str_replace([ 'M0S', 'H0M', 'T0H'], [ 'M', 'H', 'T' ], "T$time"),"T");
    if ($res == 'P') // edge case - if we remove everything, DateInterval will hate us later
        return 'PT0S';
    return $res;
}

, T, , M :

"P5M" == date_interval_iso_format(new DateInterval("P5M")); // => true
"PT5M" == date_interval_iso_format(new DateInterval("PT5M")); // => true
+1

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


All Articles