PHP: Loop through dates (from date to date) with strtotime() function

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.

<?php
	// Set timezone
	date_default_timezone_set('UTC');
 
	// Start date
	$date = '2009-12-06';
	// End date
	$end_date = '2020-12-31';
 
	while (strtotime($date) <= strtotime($end_date)) {
		echo "$date\n";
		$date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
	}
 
?>

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 strtotime("last Tuesday"), "\n";
 
?>
Follow If Not True Then False Updates!

14 Comments

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

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

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

  4. for ($i = strtotime('2011-11-01');$i <= strtotime('2011-11-28');$i += 86400){
    
    	// do stuff here
    	echo date('Y-m-d');
    
    }
    
    • 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');
       
      }
  5. Nice post.Thanks for sharing

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

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

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

  9. Thanks it’s really helpful..

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

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

  12. very nice!
    tnx

  13. thank you, useful ^^

Leave a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>