2 回答

TA貢獻1851條經(jīng)驗 獲得超4個贊
您可以根據(jù)輸入日期字符串的長度創(chuàng)建格式函數(shù)。
$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'); }
];
然后使用這些函數(shù)創(chuàng)建您的日期
$date = $formats[strlen($a_date_string)]($a_date_string);
我將 1 附加到格式函數(shù)中的字符串以將日期設(shè)置為該月的第一天。

TA貢獻1862條經(jīng)驗 獲得超6個贊
您可以創(chuàng)建一個與此類似的腳本并多次運行它并對其進行調(diào)整,直到獲得所有日期格式。
// 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
- 2 回答
- 0 關(guān)注
- 156 瀏覽
添加回答
舉報