Class luya\web\jsonld\DurationValue

Inheritanceluya\web\jsonld\DurationValue » luya\web\jsonld\BaseValue
Available since version1.0.3
Source Code https://github.com/luyadev/luya/blob/master/core/web/jsonld/DurationValue.php

Convert Timestamp or String to duration.

Example usage:

new DurationValue(strtotime("1 hour 30 minutes", 0));

Or as string

new DurationValue("1 hour 30 minutes");

Public Methods

Hide inherited methods

Method Description Defined By
__construct() Set duration data. luya\web\jsonld\DurationValue
getValue() Get the value to assign from BaseValue. luya\web\jsonld\DurationValue

Protected Methods

Hide inherited methods

Method Description Defined By
timeToIso8601Duration() Convert time to iso date. luya\web\jsonld\DurationValue

Method Details

Hide inherited methods

__construct() public method

Set duration data.

public void __construct ( $duration )
$duration string|integer

                public function __construct($duration)
{
    $this->_duration = $duration;
}

            
getValue() public method

Get the value to assign from BaseValue.

public void getValue ( )

                public function getValue()
{
    // if its not a unix timestamp, try to convert "strtotime("1 hour 30 minutes", 0);"
    if (!is_numeric($this->_duration)) {
        $this->_duration = strtotime($this->_duration, 0);
    }
    
    return $this->timeToIso8601Duration($this->_duration);
}

            
timeToIso8601Duration() protected method

Convert time to iso date.

See also https://stackoverflow.com/a/13301472/4611030.

protected string timeToIso8601Duration ( $time )
$time integer

                protected function timeToIso8601Duration($time)
{
    $units = array(
        "Y" => 365*24*3600,
        "D" =>     24*3600,
        "H" =>        3600,
        "M" =>          60,
        "S" =>           1,
    );
    
    $str = "P";
    $istime = false;
    
    foreach ($units as $unitName => &$unit) {
        $quot  = intval($time / $unit);
        $time -= $quot * $unit;
        $unit  = $quot;
        if ($unit > 0) {
            if (!$istime && in_array($unitName, array("H", "M", "S"))) { // There may be a better way to do this
                $str .= "T";
                $istime = true;
            }
            $str .= strval($unit) . $unitName;
        }
    }
    
    return $str;
}