How to create date range using php?

I tried to make time with PHP. start date 2017-01-29 to 2017-12-29. But it happened that I could not print in February, because the maximum of the month was only 28 days. How to order printing in any case, but with a February date of up to 28.

my script:

date_default_timezone_set('UTC'); // Start date $date = '2017-01-29'; // End date $end_date = '2017-12-29'; while (strtotime($date) <= strtotime($end_date)) { echo "$date\n"; echo "<br>"; $date = date ("Ymd", strtotime("+1 month", strtotime($date))); } 

Exit:

enter image description here

+8
date php web
source share
4 answers

Use the DateTime class to find the last day of the next month:

 date_default_timezone_set('UTC'); // Start date $date = '2017-01-29'; // End date $end_date = '2017-12-29'; while (strtotime($date) <= strtotime($end_date)) { echo "$date\n"; echo "<br>"; $d = new DateTime( $date ); $d->modify( 'last day of next month' ); $date = $d->format( 'Ymd' ); } 

Now this may not be exactly what interests you, because you can try different start dates and not reach the end of the next month, or you may want to use 2/28 for the February date, but then return to the 29th for each subsequent month . But that should come close to the logic you need. I think using DateTime will be part of your answer.

+6
source share

You can try another approach where you do not need to use DateTime .

  date_default_timezone_set('UTC'); // Start date $date = '2017-01-29'; // End date $end_date = '2017-12-29'; while (strtotime($date) <= strtotime($end_date)) { echo "$date\n"; echo "<br>"; $date = date("Ymt", strtotime("+30 day", strtotime($date))); } 

Using strtotime("+30 day", strtotime($date) , you can add 30 days to the current date and get the last date of the month with t .

  2017-01-29 2017-02-28 2017-03-31 2017-04-30 2017-05-31 2017-06-30 2017-07-31 2017-08-31 2017-09-30 2017-10-31 2017-11-30 
+2
source share

use this

 date ("Ymt", strtotime("+1 month", strtotime($date))); 

instead, to get the last day of the month

 date ("Ymd", strtotime("+1 month", strtotime($date))); 
+1
source share

Try this code:

  <?php $from = new DateTime; $to = new DateTime('+1 year'); for($date=clone $from; $date<$to; $date->modify('+1 day')){ echo $date->format('Ym-d'); } ?> 
0
source share

All Articles