PHP Date Export To CSV Format

 ̄綄美尐妖づ 提交于 2019-12-24 07:03:03

问题


After export and when I open the CSV up, you'll notice column L formats only some of the dates properly. This happend on a couple other date columns as well. Is there anything I can do with PHP to ensure all dates are returned properly? Below id my function:

public function formatDateCI($date) {

    // If Birthdate Column
    if(strlen($date) == 10){
        $date = explode('-',$date);
        $m = $date[0];
        $d = $date[1];
        $Y = $date[2];
        $date = $Y.'-'.$m.'-'.$d;
    }

    $date = new DateTime($date);
    // Final Format 1983-24-12 00:00:00
    return date_format($date, 'Y-d-m H:i:s');
}


回答1:


Try:

date('Y-m-d H:i:s', strtotime($date));

Instead of:

$date = new DateTime($date);

>

Be sure to try an if else structure:

if(strlen($date) == 10){
        $date = explode('-',$date);
        $M= $date[0];
        $D = $date[1];
        $Y = $date[2];
       //this $date = $Y.'-'.$m.'-'.$d;
       //or this =>
       $date = date('Y-m-d H:i:s', mktime($h, $m, $s, $M, $D, $Y));
    }else{
         $date = date('Y-m-d H:i:s', strtotime($date));
    }

    return $date;



回答2:


Simple solution would be to do just this

public function formatDateCI($date) {
    return date('%Y-%m-%d 00:00:00', strtotime($date));
}

In which case you probably dont even need to make it a method as it will fit nicely in the calling code.

ADDITIONAL INFO

If you are using an American date format you will have to correct the format for strtotime() as it expects USA format dates to have a / seperator and not a - seperator. If it see a - seperator it expects a logical date format of some sort.

public function formatDateCI($date) {
    // correct USA date format for strtotime
    $date = str_replace('-','/',$date);
    return date('%Y-%m-%d 00:00:00', strtotime($date));
}


来源:https://stackoverflow.com/questions/26238178/php-date-export-to-csv-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!