I am trying to pick either Friday / Saturday or 3rd, 18th, 30th, 31st... which ever comes first.
Real example: Current date is Tuesday, January 10th, 2017.
Options:
My code should pick the Friday, January 13th 2017.
PHP
$dayOfWeekArray = ['friday', 'saturday'];
$dayOfMonthArray = [3, 18, 30, 31];
foreach ($dayOfWeekArray as $dayOfWeek) {
$nextDayDate = new DateTime("next $dayOfWeek");
foreach ($dayOfMonthArray as $dayOfMonth) {
# Continue if $nextDayDate is before, or equals, whichever date $dayOfMonth turns out to be.
# Otherwise, determine which comes first, $nextDayDate or $dayOfMonth
}
}
Question: How can I turn $dayOfMonth
into a date?
I would use DatePeriod
to loop through days at an interval of 1 day until the formatted date matches one of the values you are looking for —
$start = new \DateTime("2017-01-10");
// You can probably do some math to determine the minimum number needed here
// php version 7.1.5
// $end = (clone $start)->modify("+31 days");
// php version 5.6
$end = clone $start;
$end->modify("+31 days");
$interval = new \DateInterval("P1D"); // An interval of 1 day
$period = new \DatePeriod($start, $interval, $end);
foreach ($period as $date) {
if (in_array($date->format('l'), ['Friday', 'Saturday']) || in_array((int) $date->format('d'), [3, 18, 30, 31])) {
break;
}
}
echo $date->format('l, Y-m-d') ;
// outputs 'Friday, 2017-01-13'
I think you’re asking that the final date not be 2017-01-13 if the current day is already 2017-01-13 — in which case you can just add a day to the start day, like $start = (new \DateTime("today"))->modify("+1 day")
Assuming that you want to know the dayOfMonth for the current month and year you could use DateTime's createFromFormat
function (http://php.net/manual/en/datetime.createfromformat.php) eg
$dayOfWeekArray = ['friday', 'saturday'];
$dayOfMonthArray = [3, 18, 30, 31];
$currentDate = new DateTime('now');
foreach ($dayOfWeekArray as $dayOfWeek) {
...
foreach ($dayOfMonthArray as $dayOfMonth) {
$nextDayOfMonthDateString = $dayOfMonth.'-'.$currentDate->format('m-Y');
$nextDayOfMonthDate = DateTime::createFromFormat('d-m-Y', $nextDayOfMonthDateString);
...
}
}