简体   繁体   English

PHP:返回日期范围的日期时间开始和日期时间结束

[英]PHP: Return date time start and date time end for a date range

I need to return date time start and date time end for each date in a given range:我需要为给定范围内的每个日期返回日期时间开始和日期时间结束:

The input would be:输入将是:

$start = '2010-11-07 10:00:00';
$end   = '2010-11-09 19:00:00';

The expected output would be:预期输出将是:

Array
(
    Array
        (
            '2010-11-07',
            '2010-11-07 10:00:00' ,
            '2010-11-08 00:00:00'
        )

    Array
        (
            '2010-11-08' ,            
            '2010-11-08 00:00:00' ,
            '2010-11-09 00:00:00'
        )

    Array
        (
            '2010-11-09' ,
            '2010-11-09 00:00:00' ,
            '2010-11-09 19:00:00'
        )

)

I managed to divide the time range into separate days using this thread: https://stackoverflow.com/a/4312630/3132858我设法使用此线程将时间范围划分为不同的日子: https : //stackoverflow.com/a/4312630/3132858

However, I cannot get the start and end time for each date.但是,我无法获得每个日期的开始和结束时间。 Any help will be appreciated!任何帮助将不胜感激!

Here is a PHP Fiddle with my code.这是一个带有我的代码的PHP Fiddle

One way to solve this is to simply loop through the days between the start/end dates:解决此问题的一种方法是简单地遍历开始/结束日期之间的天数:

function getRange($start, $end) {
    $range = [];
    $start_date = \DateTime::createFromFormat('Y-m-d H:i:s', $start);
    $end_date = \DateTime::createFromFormat('Y-m-d H:i:s', $end);
    $diff = $end_date->diff($start_date);
    for($i = 0; $i <= $diff->days; $i++) {
        $event_end = clone $start_date;
        $event_end->add(new \DateInterval("P1D"));
        if ($event_end > $end_date) {
            $range[] = [
                $start_date->format('Y-m-d'),
                $start_date->format('Y-m-d 00:00:00'),
                $end_date->format('Y-m-d H:i:s'),
            ];
            break;
        }
        $range[] = [
            $start_date->format('Y-m-d'),
            $i > 0 ? $start_date->format('Y-m-d 00:00:00') :  $start_date->format('Y-m-d H:i:s'),
            $event_end->format('Y-m-d 00:00:00')

        ];
        $start_date->add(new \DateInterval("P1D"));
    }
    return $range;
}

See it running here: https://3v4l.org/e85OM在此处查看它的运行情况: https : //3v4l.org/e85OM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM