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

标签 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 行并一一获取日期。如何将这些日期转换为特定格式? 最好是年-月-日 我正在使用 PHP 并在处理后将日期存储到 mysql 中。

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

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

最佳答案

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

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

关于php - 如何在 PHP 中格式化包含不同格式的文件中的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51915303/

相关文章:

mysql - 如何将主键、外键和备用键连接在一起?

mysql - 从mysql表的日期属性中获取月份和日期值

r - 格式化 geom_label 日期

php - PHP 中的命名空间语句可以是 "included"吗?

php - 使用 php 和 sql 时不会显示 Google Charts

php - 每次页面刷新后 session 不保留值

MySQL:没有项目的员工和没有员工的项目

java - 如何使用 Java 获取输入的日期字符串即将到来的特定工作日

PHP 不处理来自 multipart/form-data 表单的数据

php - 在 printf() 中调用 function()