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

sz81bmfz  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(376)

这个问题在这里已经有答案了

在php中将一种日期格式转换为另一种格式(16个答案)
两年前关门了。
我有一个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));
i7uq4tfw

i7uq4tfw1#

你可以试试这个。
$date=date\u create(从excel中传递日期);日期格式($date,“y/m/d h:i:s”);

cld4siwp

cld4siwp2#

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

$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
}

相关问题