PHP: Loop through dates (from date to date) with strtotime() function - Comment Page: 2

This is very easy way loop through dates (from date to date) with PHP strtotime() function. This example only echo dates, but of course this model can be used more complicated situations. [inttf_post_ad1] <?php // Set timezone date_default_timezone_set('UTC'); // Start date $date = '2009-12-06'; // End date $end_date = '2020-12-31'; while (strtotime($date) [inttf_post_ad2] Note: All different PHP strtotime() function syntaxes can be used. <?php // Set timezone date_default_timezone_set('UTC'); echo strtotime("now") . "\n"; echo strtotime("10 October 2010") . "\n"; echo strtotime("next Friday") . "\n"; echo...

34 comments on “PHP: Loop through dates (from date to date) with strtotime() function - Comment Page: 2

1 2
    1. I used to use this method myself, but then I realised that when the date crosses between daylight savings time and standard time, there’s at least one extra hour in the day. In the UK, for example, adding 86400 seconds to 2014-10-25 returns 2014-10-25 23:00:00.

      Reply
    2. If you want to use a for loop instead, try this:


      for ($date = strtotime("2014-01-01"); $date < strtotime("2014-02-01"); $date = strtotime("+1 day", $date)) {
      echo date("Y-m-d", $date)."";
      }

      Reply
    3. thanks a lot.this example saved me.keep up the good work guys :)

      Reply
    4. please help me get, this loop
      ex,
      star date column I end date column
      2015-02-01 I 2015-02-05
      2015-02-06 I 2015-02-09

      i need to echo these between all days like..
      2015-02-01, 2015-02-02, 2015-02-03, 2015-02-04, 2015-02-05, 2015-02-06, 2015-02-07, 2015-02-08, 2015-02-09

      Reply
      • plz help me i want to this code
        ex,
        star date column I end date column
        2015-02-01 I 2015-02-05
        2015-02-06 I 2015-02-09

        i need to echo these between all days like..
        2015-02-01, 2015-02-02, 2015-02-03, 2015-02-04, 2015-02-05, 2015-02-06, 2015-02-07, 2015-02-08, 2015-02-09

        Reply
    5. Hi JK,

      Nice guide thanks for sharing this.

      Reply
    6. Thank’s, Good Article :D
      It’s very helpfull.

      Reply
    7. Aaaaannd finally got it. thanks!

      Reply
    8. Very Nice and Very helpful to me…

      Reply
    9. Cool!! You saved my day!! Thank You so much!

      Reply
    10. Optimized version

      <?php
      $ts = strtotime('2009-12-06');
      $end_ts = strtotime('2020-12-31');
      while ($ts <= $end_ts) {
      echo date('Y-m-d', $ts) . PHP_EOL;
      $ts = strtotime('+1 day', $ts);
      }

      Reply
      • Thanks, I will update this to original function.

        Reply
    11. I am searching for this in many site but this one is best.

      Reply
1 2

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Close