-1

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.

Muthu
  • 29
  • 4

3 Answers3

1

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
)
0

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
)
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
0
$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
)
Muthu
  • 29
  • 4