簡體   English   中英

如何將字符串日期(來自數據庫)拆分為年,月和日

[英]How to split a string date(from Database) into year, month and day

嗨,我有以下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;
}

現在我對$ arr進行了硬編碼,如何將$ propertyValue(返回一個字符串日期(2016-10-05T00:00:00 + 00:00))拆分為$ arr,以便可以獲取每個單獨的值像那樣? 有想法嗎? 提前致謝

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;

}

您可以使用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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM