0

我想将字符串日期从多种日期格式转换为以下格式“Ymd”,例如

12-3-17、12-3-2017、12.3.17、12.3.2017、12.03.17、12/3/17

$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');

到目前为止,我得到的最接近的解决方案来自以下文章,请在此处阅读文章

考虑到输入日期字符串可能是未知格式,是否有更好的解决方案?

4

1 回答 1

0

我希望这可以帮助你。在dateFormat()函数中,您可以分配不同类型的有效格式。

function dateFormat() {
    $date_format['d.m.Y'] = 'd.m.Y';
    $date_format['d.m.y'] = 'd.m.y';
    $date_format['d-m-Y'] = 'd-m-Y';
    $date_format['d-m-y'] = 'd-m-y';
    $date_format['d/m/Y'] = 'd/m/Y';
    $date_format['d/m/y'] = 'd/m/y';

    return $date_format;
}

之后你使用这个函数如下代码

$source = '2017-03-31';
$date = new DateTime($source);
$date_format = dateFormat();
foreach($date_format as $k => $v) {
    $date_list[] = $date->format($k); 
}
print_r($date_list);
exit;

输出:-

Array
(
    [0] => 31.03.2017
    [1] => 31.03.17
    [2] => 31-03-2017
    [3] => 31-03-17
    [4] => 31/03/2017
    [5] => 31/03/17
)

现场演示

于 2017-03-31T10:41:00.773 回答