是否可以从DateInterval对象中获取“interval_spec”字符串?

时间:2013-03-06 15:38:42

标签: php string dateinterval

假设我有DateInterval的这个对象实例:

$obj=new DateInterval("P1Y12D");

现在我可以使用$obj实例做一些漂亮的事情,但是我想要从对象中获取"P1Y12D"字符串,是否可以直接实现,而无需覆盖类? / p>

我找不到一种方法,也许你这样做。

4 个答案:

答案 0 :(得分:9)

这是我的@Yaslaw's code版本。

根据当前的PHP社区和PSR要求进行了改进。我也试图让它更具可读性和直接性。

/**
 * @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;
}

这是初始\DateInterval类的扩展名:

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;
    }
}

可以像这样使用:

$interval = new CustomDateInterval('P1Y2M3DT4H5M6S');

// Prints "P1Y2M3DT4H5M6S".
print $interval . PHP_EOL;

我希望它会帮助别人,欢呼!

答案 1 :(得分:4)

您可以使用format()函数:

echo $obj->format('P%yY%mM%dDT%hH%iM%sS');

或更好的可读版本(字符串中没有零值):

function getSpecString(DateInterval $delta){
    //Read all date-parts there are not 0
    $date = array_filter(array('Y' => $delta->y, 'M' => $delta->m, 'D' => $delta->d));
    //Read all time-parts there are not 0
    $time = array_filter(array('H' => $delta->h, 'M' => $delta->i, 'S' => $delta->s));

    //Convert each part to spec-Strings
    foreach($date as $key => &$value) $value = $value.$key;
    foreach($time as $key => &$value) $value = $value.$key;

    //Create date spec-string
    $spec = 'P' . implode('', $date);            
    //add time spec-string
    if(count($time)>0) $spec .= 'T' . implode('', $time);
    return $spec;        
}   

答案 2 :(得分:2)

我不是C大师但是在构造函数的源代码中,值似乎根本没有存储:

/* {{{ proto DateInterval::__construct([string interval_spec])
   Creates new DateInterval object.
*/
PHP_METHOD(DateInterval, __construct)
{
    char *interval_string = NULL;
    int   interval_string_length;
    php_interval_obj *diobj;
    timelib_rel_time *reltime;
    zend_error_handling error_handling;

    zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC);
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &interval_string, &interval_string_length) == SUCCESS) {
        if (date_interval_initialize(&reltime, interval_string, interval_string_length TSRMLS_CC) == SUCCESS) {
            diobj = zend_object_store_get_object(getThis() TSRMLS_CC);
            diobj->diff = reltime;
            diobj->initialized = 1;
        } else {
            ZVAL_NULL(getThis());
        }
    }
    zend_restore_error_handling(&error_handling TSRMLS_CC);
}
/* }}} */

似乎都没有执行date_interval_initialize()功能:

static int date_interval_initialize(timelib_rel_time **rt, /*const*/ char *format, int format_length TSRMLS_DC)
{
    timelib_time     *b = NULL, *e = NULL;
    timelib_rel_time *p = NULL;
    int               r = 0;
    int               retval = 0;
    struct timelib_error_container *errors;

    timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors);

    if (errors->error_count > 0) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format);
        retval = FAILURE;
    } else {
        if(p) {
            *rt = p;
            retval = SUCCESS;
        } else {
            if(b && e) {
                timelib_update_ts(b, NULL);
                timelib_update_ts(e, NULL);
                *rt = timelib_diff(b, e);
                retval = SUCCESS;
            } else {
                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse interval (%s)", format);
                retval = FAILURE;
            }
        }
    }
    timelib_error_container_dtor(errors);
    return retval;
}

答案 3 :(得分:0)

没有内置功能,您必须自己创建一个。 如果您不想覆盖DateInterval,请尝试使用静态方法:

class DateIntervalUtils{
    public static function getSpecString(DateInterval $i){
         $stat ="P";
         foreach($i as $key=>$value){
            if($key !=="days"){
               if($key=="h"){
                  $stat.="T";
               }
               $stat.=$value.upper($key);
             }
          }
          return $stat;
      }
  }

如果你想添加功能(比较等),你可以添加它。