2016-11-25 28 views
0

嗨,我有以下的php事件如何分割字符串日期(从数据库)为年,月,日

public function onRenderDate(Event $event, $propertyValue) 
{ 
    // $propertyValue will be something like 1970-01-01,need to split the value in to following format 
    pr($propertyValue); 
    pr(getType($propertyValue)); 

    $arr = [ 
     'year' => 2016, 
     'month' => 07, 
     'day' => 01 
    ]; 

    return $arr; 
} 

现在我存的是$编曲,我怎么能拆我的$的PropertyValue(返回一个字符串日期(2016-10-05T00:00:00 + 00:00))到$ arr中,这样我可以得到每个单独的值吗?任何想法的家伙?在此先感谢

+0

请务必提及您的确切CakePHP版本!在CakePHP 3.x中,假设您使用正确的列类型,数据库中的日期值将是对象。 ** HTTP://book.cakephp.org/3.0/en/core-libraries/time.html** – ndm

回答

1
public function onRenderDate(Event $event, $propertyValue) 
{ 
    $time = strtotime($propertyValue); 
    $newformat = date('Y-m-d',$time); 
    $newformatArr = explode('-',$newformat); 


     $arr = [ 
      'year' => $newformatArr[0], 
      'month' => $newformatArr[1], 
      'day' => $newformatArr[2] 
     ]; 

    return $arr; 

} 
0

您可以使用strtotime()PHP函数来做到这一点。该函数预期会给出一个包含英文日期格式的字符串,并将尝试将该格式解析为Unix时间戳。使用时间戳,您可以使用date()函数获取日,月和年。下面我有更新你的功能。

public function onRenderDate(Event $event, $propertyValue) 
{ 
    $timestamp = strtotime($propertyValue); 

     $arr = [ 
      'year' => date('Y', $timestamp), 
      'month' => date('m', $timestamp), 
      'day' => date('d', $timestamp) 
     ]; 

    return $arr; 

} 
相关问题