I have some code that loops through each day within a 10 year range starting on a specific date. The date should only be added if it meets the selected criteria from a form.
The form has fields for months and weekdays to be selected. Within each weekday there are options for every, first, second, etc. I'm adding an 'every other' option to each weekday along with a start date field.
I am trying to determine the best way to check if the current date is within the 'every other' criteria based on the start date.
After looking at other questions, I couldn't find an ideal answer that took into account year that have 53 weeks. I was able to come up with some test code that seems to be giving me accurate results, but I'm wondering if there is a simpler way to perform this check.
Test Code:
// set start date
$date = new \DateTime('2019-12-15');
// get start date week of year and modulus
$start_week = date('W', $date->getTimestamp());
$start_mod = $start_week % 2;
// set end time (10 years from start date)
$end_time = strtotime('+10 years', $date->getTimestamp());
// init previous year and week modifier
$prev_year = false;
$week_modifier = 1;
// each day in range
while($date->getTimestamp() <= $end_time){
// get year
$y = $date->format('Y');
// previous year doesn't match current year
if($prev_year != $y){
// previous year set
if($prev_year){
// get number of weeks in year
$weeks_in_year = date('W', mktime(0, 0, 0, 12, 28, $prev_year));
// year has odd number of weeks
if($weeks_in_year % 2){
// increment week modifier
$week_modifier++;
}
}
// update previous year
$prev_year = $y;
}
// get week of year
$w = $date->format('W') + $week_modifier;
// check if meets every other criteria (based on start date)
$every_other = false;
if( ($w % 2) == $start_mod ){
$every_other = true;
}
// print date if it is part of every other Tuesday
if($date->format('w') == 2 && $every_other){
echo $date->format('Y-m-d');
echo '<br/>';
}
// increment day
$date->modify('+1 day');
}
Note 1: 2020 is the next year in which there are 53 weeks.
Note 2: I had a typo in this test code that was incrementing the week modifier instead of initializing it to 0. It would make more sense to me that this code would work if the modifier was initialized to be 0, but instead it only works when initialized to an odd number.