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

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: 1

1 2
    1. Nice post. Been learning basic PHP. Your guides really help

      Reply
    2. This is cool, i didn’t know you could do that! Very useful!

      Reply
    3. fantastic code.. working perfectly. thanks to JR to post such useful php code :)

      Reply
    4. for ($i = strtotime('2011-11-01');$i <= strtotime('2011-11-28');$i += 86400){
      
      	// do stuff here
      	echo date('Y-m-d');
      
      }
      
      Reply
      • Hi yo,

        Yes you can do it many ways, but my example try to show method which works nicely even if you change +1 day to +4 days, 1 week, 1 month, 2 years, etc.

        Most powerful way to do this is minimize strtotime and date functions usage. So your example is good, but following is even more efficient:

        
        $start = strtotime('2011-11-01');
        $end = strtotime('2011-11-28');
        for ( $i = $start; $i < = $end; $i += 86400 ){
        
        	// do stuff here
        	echo date('Y-m-d');
        
        }
        
        Reply
    5. Nice post.Thanks for sharing

      Reply
    6. Thanks, it’s useful to me ^^~

      Reply
    7. TY ! This script really helped me !
      I’m using it in combination with gvChart. =)

      Reply
    8. Works like a charm. Thanks for the simple solution!

      Reply
    9. Thanks it’s really helpful..

      Reply
    10. Thanks A lot . I used it today in my program.Cheers !

      Reply
    11. This is so cool! Just what I needed for making a statistics graph! Thanks loads!

      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