Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extend the \DateInterval class to have a __toString() method, returning the string representation of the object
<?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