Created
December 14, 2021 09:37
-
-
Save amnuts/7d3f50fb1b722e78686678b07a4879a4 to your computer and use it in GitHub Desktop.
Extend the \DateInterval class to have a __toString() method, returning the string representation of the object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use DateInterval; | |
class DateTimeInterval extends DateInterval | |
{ | |
/** | |
* Return the textual representation of an interval object | |
* | |
* @return string | |
*/ | |
public function __toString(): string | |
{ | |
$dateParts = array_filter([ | |
'Y' => $this->y, | |
'M' => $this->m, | |
'D' => $this->d | |
]); | |
$timeParts = array_filter([ | |
'H' => $this->h, | |
'M' => $this->i, | |
'S' => $this->s | |
]); | |
$string = 'P'; | |
if (!empty($dateParts)) { | |
foreach ($dateParts as $which => $val) { | |
$string .= sprintf('%d%s', $val, $which); | |
} | |
} | |
if (!empty($timeParts)) { | |
$string .= 'T'; | |
foreach ($timeParts as $which => $val) { | |
$string .= sprintf('%d%s', $val, $which); | |
} | |
} | |
return $string; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment