PHP - 接受输入和输出日期的各种日期格式

  • 本文关键字:日期 格式 输出 PHP php
  • 更新时间 :
  • 英文 :


我有一个庞大的excel文件,我导入并存储到日期字段(date("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);
}

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

$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,以将日期设置为每月的第一天。

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

// 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 

最新更新