2016-11-25 29 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; 

} 
相關問題