【问题标题】:How to format dates from a file containing different formats in PHP? [duplicate]如何格式化包含 PHP 中不同格式的文件中的日期? [复制]
【发布时间】:2018-08-19 06:59:49
【问题描述】:

我有一个 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));

【问题讨论】:

  • 这些是您可能遇到的所有格式还是可能有更多变化?
  • 是的,只有这些。
  • 只需str_replace .-/
  • 如果在第 2 行和第 3 行之间添加额外的行怎么办:$date = str_replace('.', '-', $date);
  • 有更多格式编辑有问题。

标签: php mysql date strtotime date-formatting


【解决方案1】:

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

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

【讨论】:

  • 太棒了!请记住,这不适用于美国格式日期 (mm/dd/yy)。
【解决方案2】:

你可以试试这个。

$date=date_create(从你的 excel 中传递日期); date_format($date,"Y/m/d H:i:s");

【讨论】:

  • 试过了,Parse error: syntax error, unexpected 'the' (T_STRING), expecting ')' in
  • $array = array("-","."); $date = str_replace($array,'/','10.12.2014'); $date = date_create($date); echo date_format($date,'Y-m-d');输出:2014-10-12 @kiran-g
猜你喜欢
  • 2011-02-21
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 2023-01-23
  • 2010-11-08
  • 2018-05-05
相关资源
最近更新 更多