2 回答
TA贡献1794条经验 获得超7个赞
我真的建议将您的日期存储为两个单独的值(开始/结束),然后对输出进行格式化,而不是尝试解码格式化的输出。
如果您坚持使用这种方法,您可以使用preg_match
匹配不同的格式,然后从匹配的值中提取开始和结束日期:
$dates = array(
'28 April 2020',
'3 - 5 May 2020',
'3 May - 5 June 2020',
'20 Dec 2020 - 15 Jan 2021'
);
foreach ($dates as $date) {
preg_match('/^(\d+)\s(\w+)\s(\d+)(?:\s-\s(\d+)\s(\w+)\s(\d+))?|(\d+)\s(\w+)\s-\s(\d+)\s(\w+)\s(\d+)|(\d+)\s-\s(\d+)\s(\w+)\s(\d+)$/', $date, $matches);
if (isset($matches[12])) {
// dd - dd mmm yyyy format
$start_date = "${matches[12]} ${matches[14]} ${matches[15]}";
$end_date = "${matches[13]} ${matches[14]} ${matches[15]}";
}
elseif (isset($matches[7])) {
// dd mmm - dd mmm yyyy format
$start_date = "${matches[7]} ${matches[8]} ${matches[11]}";
$end_date = "${matches[9]} ${matches[10]} ${matches[11]}";
}
elseif (isset($matches[4])) {
// dd mmm yyyy - dd mmm yyyy format
$start_date = "${matches[1]} ${matches[2]} ${matches[3]}";
$end_date = "${matches[4]} ${matches[5]} ${matches[6]}";
}
elseif (isset($matches[1])) {
// dd mmm yyyy format
$start_date = "${matches[1]} ${matches[2]} ${matches[3]}";
$end_date = "${matches[1]} ${matches[2]} ${matches[3]}";
}
else {
// no match
$start_date = '???';
$end_date = '???';
}
echo "$start_date - $end_date\n";
}
输出:
28 April 2020 - 28 April 2020
3 May 2020 - 5 May 2020
3 May 2020 - 5 June 2020
20 Dec 2020 - 15 Jan 2021
TA贡献1804条经验 获得超7个赞
你可以尝试这样的事情:
$inputDateString = "28 April 2020";
$dateObject = DateTime::createFromFormat("j F Y",$inputDateString);
echo $dateObject->format('d m Y') . " - " . $inputDateString->format('d m Y');
$inputDateString1 = "3 May";
$dateObject1 = DateTime::createFromFormat("j F",$inputDateString1);
$inputDateString2 = "5 May 2020";
$dateObject2 = DateTime::createFromFormat("j F Y",$inputDateString2);
echo $dateObject1->format('d m ').date('Y'); . " - ". $dateObject2->format('d m Y');
计算间隔
$interval = $dateObject2->diff($dateObject1);
echo $interval->format('%d days');
- 2 回答
- 0 关注
- 101 浏览
添加回答
举报