-1

I have this script which returns time range between 2 dates, but adding 1 day!!

$date_1 = date("Y-m-d g:i:s", strtotime('2013-06-27 12:00:00'));
$date_2 = date("Y-m-d g:i:s", strtotime('2013-06-29 12:00:00'));
$results = array($date_1);
$i = $date_1;
  while ($i <= $date_2) {
    $i = date("Y-m-d g:i:s", strtotime("+1 day", strtotime($i)));// how do I take off here this "+1 day"
    array_push($results, $i);
    echo $i;
}

So when I echo out $i I get the following string

2013-06-28 2013-06-29 2013-06-30  

while I Need

2013-06-27 2013-06-28 2013-06-29

The problem is obviously this "+1 day" but if I take it off from my function a get error.

How to solve this?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user2959620
  • 29
  • 1
  • 2
  • 6
  • Ummm.. push `$i = ` to the end instead? BTW - `strtotime($i . ' +1 day')` would work just as fine as `strtotime('+1 week', strtotime($i))` except it only takes 1 `strtotime` call. – h2ooooooo Nov 12 '13 at 17:29

4 Answers4

0

try changing this

strtotime("+1 day", strtotime($i))

to this :

strtotime("+0 day", strtotime($i))
Aditya Vikas Devarapalli
  • 3,186
  • 2
  • 36
  • 54
0

I tried this:

$date_1 = date("Y-m-d g:i:s", strtotime('2013-06-27 12:00:00'));
$date_2 = date("Y-m-d g:i:s", strtotime('2013-06-29 12:00:00'));
$results = array($date_1);
$i = $date_1;
while ($i <= $date_2) {
    $i = date("Y-m-d g:i:s", strtotime($i));// how do i take off here this "+1 day"                                                    
    array_push($results, $i);
    echo $i . "\n";
    $i = date("Y-m-d g:i:s",strtotime("+1 day", strtotime($i)));
}

and gave me:

2013-06-27 12:00:00
2013-06-28 12:00:00
2013-06-29 12:00:00
gryphes
  • 27
  • 2
0

You need to increase variable $i:

$date_1 = strtotime('2013-06-27 12:00:00');
$date_2 = strtotime('2013-06-29 12:00:00');
$results = array();
$i = $date_1;
  while ($i <= $date_2) {
    array_push($results, date("Y-m-d g:i:s", $i));
    $i = strtotime('+1 day', $i);
}


print_r($results);
Alexander
  • 807
  • 5
  • 10
0

Just to let you know:

date_default_timezone_set('UTC');
$date_from = '2013-06-27 12:00:00';
$date_interval = '+1 day';
$date_to = '2013-06-29 12:00:00';
$date_range = array_map(function ($date) {
        return $date->format('Y-m-d g:i:s');
    }, iterator_to_array(
        new DatePeriod(new DateTime($date_from),
                       DateInterval::createFromDateString($date_interval),
                       (new DateTime($date_to))->modify('+1 day'))));
var_dump($date_range);

Gave me the following:

array(3) {
  [0]=>
  string(10) "2013-06-27 12:00:00"
  [1]=>
  string(10) "2013-06-28 12:00:00"
  [2]=>
  string(10) "2013-06-29 12:00:00"
}

PHP 5.3+ compatible.

Paulo Freitas
  • 13,194
  • 14
  • 74
  • 96