PHP日期导出为CSV格式

时间:2014-10-07 14:18:04

标签: php datetime csv export-to-csv date-formatting

导出后,当我打开CSV时,您会注意到L列只能正确格式化某些日期。这也发生在其他几个日期列上。有什么我可以用PHP来确保所有日期都正确返回?下面是我的功能:

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

Column L Date Format Issue

2 个答案:

答案 0 :(得分:2)

尝试:

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

而不是:

$date = new DateTime($date);

>

请务必尝试if else结构:

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;

答案 1 :(得分:0)

简单的解决方案就是做到这一点

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

在这种情况下你可能甚至不需要把它变成一个方法,因为它很适合调用代码。

附加信息

如果您使用的是美国日期格式,则必须更正strtotime()的格式,因为它希望美国格式的日期包含/分隔符,而不是-分隔符。如果它看到-分隔符,则它需要某种逻辑日期格式。

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