如何格式化PHP中包含不同格式的文件中的日期?

时间:2018-08-19 06:59:50

标签: php mysql date strtotime date-formatting

我有一个excel文件,其中的日期没有特定顺序的多种格式。 格式各异

dd/mm/yyyy
dd/mm/yy
dd.mm.yyyy
dd.mm.yy
dd-mm-yyyy
dd-mm-yy
dd.Jan.18
dd-Jan-2018

我遍历excel行并逐个获取日期。如何将这些日期转换为特定格式? 最好是yyyy-mm-dd 我正在使用PHP,并将处理后的日期存储到mysql中。

我已经尝试过这种方法,但不适用于dd.mm.yy

$date = $row[$datepos];
$date = str_replace('/', '-', $date);
$date = date("Y-m-d",strtotime($date));

2 个答案:

答案 0 :(得分:3)

如果这些是您必须处理的 only 日期,则以下代码将起作用:

$dates = [
    "01/01/2018",
    "01/01/18",
    "01.01.2018",
    "01.01.18",
    "01-01-2018",
    "01-01-18",
    "01.Jan.18",
    "01-Jan-18",
];

foreach($dates as $date){
    $dt_array = preg_split("/[^A-Za-z0-9]/", $date);
    //Break apart the date string using any non-alphanumeric character as the delimiter

    var_dump($dt_array);
    //Just for demonstration purposes

    $day = $dt_array[0];
    // Grab the day

    if(is_numeric($dt_array[1])){
        $month = $dt_array[1];
    } else {
        $dp = date_parse($dt_array[1]);
        $month = $dp['month'];
    }
    //The month is a little bit more complex,
    //because at times it's an integer, at times it's a string,
    //and we want it to always be a integer

    $year = $dt_array[2];
    //Grab the year

    $dt = new DateTime("{$year}-{$month}-{$day}");
    //The y-m-d format is flexible,
    //because it will accept yyyy and yy
    //and since your m and d are integers,
    //it will work even if they don't have a leading zero.

    var_dump($dt->format('Y-m-d'));
    //Just for demonstration purposes
}

答案 1 :(得分:0)

您可以尝试一下。

$ date = date_create(通过Excel输入日期); date_format($ date,“ Y / m / d H:i:s”);