Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the "interval_spec" string from DateInterval object?

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.

like image 916
TechNyquist Avatar asked Mar 06 '13 15:03

TechNyquist


1 Answers

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!

like image 137
Slava Fomin II Avatar answered Sep 28 '22 04:09

Slava Fomin II