【问题标题】:PHP - Accept various date formats for input and output datePHP - 接受输入和输出日期的各种日期格式
【发布时间】:2019-09-05 23:13:55
【问题描述】:

我有一个庞大的 Excel 文件,我正在导入并存储到日期字段(日期(“​​Y-m-d”))。 问题是,输入有几种不同的格式,例如:

1) 2015/01/01 // valid format, php converts this to yyyy-mm-dd
2) 2015-01 // supposed to be 2015-01-01
3) jan/18 // supposed to be 2018-01-01

如您所见,虽然大多数以有效格式提供,但(大部分)使用的其他两种格式是“年-月”和“月/年”。 一切都表明strtotime,下面应该工作 - 但是如果我的理解是正确的,我将如何指示当月的“第一天”没有提供这一天(因为否则它最终会为所有内容都为空,但上面的(1)如果我的理解是正确的)?

//assumes $str is one of the above mentioned formats
if (($timestamp = strtotime($str)) === false) {
    $date = null;
} else {
    $date = date('Y-m-d', $timestamp);
}

【问题讨论】:

  • 您需要对每种情况使用 preg_match 和正则表达式,并逐个应用修改
  • 正则表达式是解决问题的方法(需要找到模式)它并不难
  • 你知道所有的日期格式吗?
  • 只是上面列出的 3 个@Claudio

标签: php


【解决方案1】:

您可以根据输入日期字符串的长度创建格式函数。

$formats = [
    10 => function($string) { return date_create_from_format('Y/m/d', $string); },
    7 => function($string) { return date_create_from_format('Y-m j', $string . ' 1'); },
    6 => function($string) { return date_create_from_format('M/y j', $string . ' 1'); }
];

然后使用这些函数创建您的日期

$date = $formats[strlen($a_date_string)]($a_date_string);

我将 1 附加到格式函数中的字符串以将日期设置为该月的第一天。

【讨论】:

    【解决方案2】:

    您可以创建一个与此类似的脚本并运行多次调整它,直到获得所有日期格式。

    // should be listed from more specific to least specific date format
    $dateFormats = [
        'Y/m/d' => ['midnight'],
        'Y-m'   => ['midnight', 'first day of this month'],
        'M/y'   => ['midnight', 'first day of this month'],
    ];
    
    $dates = [
        '2015/01/01',
        '2015-01',
        'jan/18',
    ];
    
    foreach ($dates as $date) {
        if ($dateTime = getDateTimeFrom($date, $dateFormats)) {
            echo "{$dateTime->format('Y-m-d H:i:s')} \n";
        } else {
            echo "Unknown date format : {$date} \n";
        }
    }
    
    
    function getDateTimeFrom(string $dateString, array $dateFormats) : ?\DateTime {
        if (!$dateString) {
            return null;
        }
    
        foreach ($dateFormats as $format => $modifiers) {
            if ($dateTime = \DateTime::createFromFormat($format, $dateString)) {
                foreach ($modifiers as $modification) {
                    $dateTime->modify($modification);
                }
    
                return $dateTime;
            }
        }
    
        return null;
    }
    
    // Outputs:
    // 2015-01-01 00:00:00 
    // 2015-01-01 00:00:00 
    // 2018-01-01 00:00:00 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多