我有以下格式的一系列活动日期(可变持续时间):
为了便于阅读,我想保留这种方式。
但是我的日历需要阅读这些内容的标准方法,因此它可以输出这些事件:
关于如何在php中执行此操作的任何想法?
我真的建议您将日期存储为两个单独的值(开始/结束),然后对输出进行格式化,而不是尝试对格式化的输出进行解码。
如果坚持使用此方法,则可以使用preg_match
来匹配不同的格式,然后从匹配的值中提取开始日期和结束日期:
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
您可以尝试这样的事情:
Demo on 3v4l.org
计算间隔
$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');