Say I have this object instance of DateInterval:
$obj=new DateInterval("P1Y12D");
Now I can do few pretty things with that $obj
instance, but say I want to get out that "P1Y12D"
string from the object, is it straight possible without the need to override the class?
I do not find a method for this, maybe you do.
Here's my version of @Yaslaw's code.
It is improved according to a current PHP community and PSR requirements. I've also tried to make it more readable and straight-forward.
/**
* @param \DateInterval $interval
*
* @return string
*/
function dateIntervalToString(\DateInterval $interval) {
// Reading all non-zero date parts.
$date = array_filter(array(
'Y' => $interval->y,
'M' => $interval->m,
'D' => $interval->d
));
// Reading all non-zero time parts.
$time = array_filter(array(
'H' => $interval->h,
'M' => $interval->i,
'S' => $interval->s
));
$specString = 'P';
// Adding each part to the spec-string.
foreach ($date as $key => $value) {
$specString .= $value . $key;
}
if (count($time) > 0) {
$specString .= 'T';
foreach ($time as $key => $value) {
$specString .= $value . $key;
}
}
return $specString;
}
And here's the extension to the initial \DateInterval
class:
class CustomDateInterval extends \DateInterval
{
public function __toString()
{
// Reading all non-zero date parts.
$date = array_filter(array(
'Y' => $this->y,
'M' => $this->m,
'D' => $this->d
));
// Reading all non-zero time parts.
$time = array_filter(array(
'H' => $this->h,
'M' => $this->i,
'S' => $this->s
));
$specString = 'P';
// Adding each part to the spec-string.
foreach ($date as $key => $value) {
$specString .= $value . $key;
}
if (count($time) > 0) {
$specString .= 'T';
foreach ($time as $key => $value) {
$specString .= $value . $key;
}
}
return $specString;
}
}
It can be used like this:
$interval = new CustomDateInterval('P1Y2M3DT4H5M6S');
// Prints "P1Y2M3DT4H5M6S".
print $interval . PHP_EOL;
I hope it will help someone, cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With