Skip to content

Instantly share code, notes, and snippets.

@amnuts
Created December 14, 2021 09:37
Show Gist options
  • Save amnuts/7d3f50fb1b722e78686678b07a4879a4 to your computer and use it in GitHub Desktop.
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
<?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