Home > other >  PHP Determine If Monday or Thursday is next from date provided
PHP Determine If Monday or Thursday is next from date provided

Time:11-20

Is PHP able to determine if a Monday or Thursday comes next and what the date ('YYYY-MM-DD') will be if I provide it with a date to start from?

CodePudding user response:

Calculate the date of the next Monday and Thursday using a given date:

$start = new DateTimeImmutable('2023-01-08');
$monday = $start->modify("next monday");
$thursday = $start->modify("next thursday");

Using diff with an if statement display the result

if ( ($start->diff($monday)->days < $start->diff($thursday)->days ) ) {
    echo "monday";
} else {
    echo "thursday";
}

CodePudding user response:

Next monday or thursday is the smaller of the two. If DateTime is used instead of DateTimeImmutable, copies (clone) from $start must be used.

$start = new DateTime('2022-11-19');
$nextMondayOrThursday = Min(
  (clone $start)->modify("next monday"),
  (clone $start)->modify("next thursday")
);

echo $nextMondayOrThursday->format('l, d F Y');
//Monday, 21 November 2022

Try self: https://3v4l.org/Y5sE5

  • Related