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";
 
?>

Related posts:

  1. PHP: Calculate Real Differences Between Two Dates or Timestamps I was using simple function to calculate difference between two dates and timestamps until I noticed, it’s not working correctly...
  2. PHP mb_ucfirst Make a String’s First Character Uppercase-Multibyte (UTF-8) Function PHP’s ucfirst function is very usefull when you want to change words first letters to uppercase and other letters to...
  3. PHP Script to Generate PostgreSQL Table Partitioning (Part 2) As Part 1 (Howto create PostgreSQL table partitioning) shows, making of PostgreSQL partitioning needs a lot of SQL commands. So...
  4. PHP Timing Class – Class for Measure PHP Scripts Execution Time and PHP Web Page Load Time In many cases, it is really useful to know the exact time for how long a PHP script is running...
  5. Format bytes with PHP – B, KB, MB, GB, TB, PB, EB, ZB, YB converter Simple PHP function that formats the bytes to the desired form. Possible unit options are: Byte (B) Kilobyte (KB) Megabyte...

About the Author

Hi, I'm JR and the Founder of if not true then false. I am a software developer, and I have over ten years experience in programming. I'm big fan of Linux and Open Source. And normally I use just Linux environments.

Like If (!1) 0 on Facebook: