Development

Date and Time – PHP way – part 3

Today third and final part. Today we will talk mainly about `DatePeriod` class. It is very powerful tool, we can use it to iterate dates. How about iterating all Fridays? We like Fridays, because weekend starts, so… it is always good to know it’s Friday 🙂 Let’s begin…

add( new DateInterval( 'P3M' ) );

echo 'Starting: ' . $start_date->format( 'Y-m-d' ) . PHP_EOL;
echo '  Ending: ' . $end_date->format( 'Y-m-d' ) . PHP_EOL;

$period_interval = DateInterval::createFromDateString( 'next friday' );

$period_iterator = new DatePeriod( $start_date, $period_interval, $end_date, DatePeriod::EXCLUDE_START_DATE );
foreach( $period_iterator as $item ) {
	echo $item->format( 'Y-m-d' ) . PHP_EOL;
}

And results:

Starting: 2017-01-01
  Ending: 2017-04-01
2017-01-06
2017-01-13
2017-01-20
2017-01-27
2017-02-03
2017-02-10
2017-02-17
2017-02-24
2017-03-03
2017-03-10
2017-03-17
2017-03-24
2017-03-31

I think this is self explanatory code. Please remember three things.
[postad1]
One – I used `next friday` as an interval. If you use `last friday` you’ll get your iterator iterating downwards, so you may end in the year of -9999 🙂

Two – `$item` is DateTime object, you may do whatever you want as it’s normal object
[postad2]
Three – this is iterator, not an array, so `count()` won’t work!