skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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";
    }
    

  2. 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

    A solution that specifies the short form of the days of the week in an array offers more flexibility. In this way, 3 or more days of the week can also be specified.

    $start = date_create('2022-11-20');
    $next = ['Mon','Thu','Fri'];
    
    while(!in_array($start->modify('+1 Day')->format('D'),$next));
    
    echo $start->format('l, d F Y');
    

    It is recommended to ensure that the while loop does not run indefinitely by validating $next.

    Future times such as next Monday or next Thursday can also be conveniently encoded as a string using cron syntax. For Monday or Thursday 00:00 the string is:

    '0 0 * * 1,4'
    

    The days of the week are written as digits from 0 for Sunday to 6 for Saturday. A big advantage is that these strings can easily be stored anywhere like in a database. There are a number of solutions to implement it in PHP (e.g. cron-expression). Just an example using the JspitDt class:

    use JspitDt;
    
    $cron = '0 0 * * 1,4'; 
    $date = Dt::create('2022-11-21')->NextCron($cron);
    //"2022-11-24 00:00:00.000000"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search