(php) 将持续时间更改为我的日历可用的时间

(php) change a duration to something useable by my calendar

我有一系列事件日期(持续时间可变),格式如下:

为了便于阅读,我想保留这些内容。

但是我的日历需要一种标准的方式来读取这些事件,以便它可以输出这些事件:

关于如何在 php 中执行此操作的任何想法?

你可以尝试这样的事情:

$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');

我真的建议将您的日期存储为两个单独的值 (start/end),然后在输出时格式化,而不是尝试解码格式化的输出。

如果您坚持使用这种方法,您可以使用 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