简体   繁体   中英

How to get datetime range between two datetimestamps with an interval in php

I am trying to write a program to dynamically add interval and find datetime between two dates in php.

I am getting Startdatetime, Enddatetime, Interval from the user.

If the Start date is 2020-02-17 00:00:00 , end date is 2020-02-17 08:00:00 , and interval to be added to is 2hrs,

then I am trying to print all datetime ranges like

Array(
    [0] => 2020-02-17 00:00:00
    [1] => 2020-02-17 02:00:00
    [2] => 2020-02-17 04:00:00
    [3] => 2020-02-17 06:00:00
    [4] => 2020-02-17 08:00:00
)

I tried with dateperiod, but doesn't work as it gives only start & end date

$period = new DatePeriod(
    new DateTime($from_datetime),
    new DateInterval('PT$hoursH'),
    new DateTime($to_datetime)
);

Please help me to get all datetime ranges.

Using this :

<?php
$begin = new DateTime('2020-02-17 00:00:00');
$end = new DateTime('2020-02-17 08:00:01');
$interval = DateInterval::createFromDateString('2 hours');
$period = new DatePeriod($begin, $interval, $end);

$myDates = [];

foreach ($period as $dt) {
    $myDates[] = $dt->format("Y-m-d H:i:s");
}

Now executing:

print_r($myDates);

gives you

Array (
    [0] => 2020-02-17 00:00:00
    [1] => 2020-02-17 02:00:00
    [2] => 2020-02-17 04:00:00
    [3] => 2020-02-17 06:00:00
    [4] => 2020-02-17 08:00:00
)

You can use the date parser of PHP, its pretty intelligent.

$startDate     = new DateTime('2020-02-17 00:00:00');
$endDate       = new DateTime('2020-02-17 08:00:00');
$intervalInHrs = 2;

while ($startDate <= $endDate) {
    $output[] = $startDate->format("Y-m-d H:i:s");
    $startDate->modify("+$intervalInHrs Hours");
}

Output:

Array
(
    [0] => 2020-02-17 00:00:00
    [1] => 2020-02-17 02:00:00
    [2] => 2020-02-17 04:00:00
    [3] => 2020-02-17 06:00:00
    [4] => 2020-02-17 08:00:00
)
$from_datetime = new DateTime('2020-02-17 00:00:00');
$to_datetime = new DateTime('2020-02-17 08:00:00');
$hours = 2;
$interval = new DateInterval('PT'.$hours.'H');
$period = new DatePeriod($from_datetime, $interval, $to_datetime);
$dateArray = [];
foreach ($period as $dt) {
    $dateArray[] = $dt->format("Y-m-d H:i:s");
}
print_r($dateArray);exit;

Above code gave me the expected output as

Array
(
[0] => 2021-02-17 00:00:00
[1] => 2021-02-17 02:00:00
[2] => 2021-02-17 04:00:00
[3] => 2021-02-17 06:00:00
[4] => 2021-02-17 08:00:00
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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