从日期字符串PHP解析日期格式

时间:2020-02-27 21:48:15

标签: php date datetime

我正在努力实现这一目标:

getFormat("Jan 2020") // returns: M Y
getFormat("01 Feb 2020") // returns: d M Y
getFormat("01-January-2020") // returns: d-F-Y

想法基本上是对php日期进行反向工程

这是我到目前为止尝试过的:

public function getFormat($date){
    $date = strtolower($date);
    $formats = array(
        "F" => array("january","february","march","april","may","june","july","august","september","october","november","december"),
        "M" => array("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"),
    );

    foreach($formats as $format=>$data) {
        foreach($data as $d)
            if (stripos($date,$d) !== false) $date = str_replace($d,$format,$date);
    }
    return $date;
}

这种方法可以工作数月或数天,但我认为该技术永远无法用于数字值。

1 个答案:

答案 0 :(得分:1)

date_parse()检查格式是否存在日,月和年。使用config数组中的正则表达式将这些部分替换为格式字符。

这不是一个完美的解决方案。这是一种可以改进的方法。

function getDateFormat($format){
    $parse = date_parse($format);
    if($parse['error_count']) return false;
    $conf = [
        '~\d{4}~' => ['year','Y'],
        '~[a-z]{4,8}~i' => ['month','F'],
        '~[a-z]{3}~i' => ['month','M'],
        '~(?<=[ /\-\.])\d{2}(?=[ /\-\.])~' => ['month','m'],
        '~\d{1,2}(?=[,])~' => ['day','j'],
        '~\d{2}~' => ['day','d'],
        '~\d{1}~' => ['day','j'],
    ];

    foreach($conf as $regEx => $types){
      if($parse[$types[0]] !== false) {
        $format = preg_replace($regEx, $types[1], $format, 1, $count);
        if($count) $parse[$types[0]] = false; ;
      }
    }
    return $format;

}

我还没有完全测试该函数可以正确处理哪些表达式。以下是一些示例:

$data = [
  "Jan 2020","01 Feb 2020","01-January-2020",
  "2020-03-02","05.06.1987", "April 6, 1967",
  "1988", "5. July 1966", 
  "is a Error"

];
foreach($data as $format){
  $frm = getDateFormat($format);
  echo $format." : ".($frm ? $frm : "ERROR")."<br>";
} 

输出:

Jan 2020 : M Y
01 Feb 2020 : d M Y
01-January-2020 : d-F-Y
2020-03-02 : Y-m-d
05.06.1987 : d.m.Y
April 6, 1967 : F j, Y
1988 : Y
5. July 1966 : j. F Y
is a Error : ERROR