skip to Main Content

If I want to default a date to the next working day I am using the following:

<?php
    echo(date('d/m/Y',strtotime('+1 Weekdays')));
?>

For example: If a user is adding an item on a Friday it is given a default of the following Monday – the next working day.

I have to create a schedule of events with a start and end date. The end date needs to 1 year in the future on the preceding working day.

For example: If a user adds a schedule that has a start day of Wednesday and the same date in a years time happens to be a Sunday, then the end date needs to default to the previous Friday – the preceding working day.

3

Answers


  1. Chosen as BEST ANSWER

    I found the answer:

    <?php
        echo(date(date('d/m/Y',strtotime('+1 year')),strtotime('-1 Weekdays')));
    ?>
    

  2. You just need to add one year to today’s date then check the day of the week, if it is ‘Sat’ or ‘Sun’ subtract one weekday. The PHP DateTime object makes this easy with the format() and modify() methods.

    $inOneYear = new DateTime('+1 year');
    if(in_array($inOneYear->format('D'), ['Sat', 'Sun'])){
        $inOneYear->modify('-1 weekday');
    }
    echo $inOneYear->format('D, d/m/Y');
    

    In all these cases:

    • today (Thursday, Dec. 1st, 2022)
    • tomorrow (Friday, Dec. 2nd, 2022)
    • the next day (Saturday, Dec. 3rd, 2022)

    the above will output:

    Fri, 01/12/2023
    
    Login or Signup to reply.
  3. The strtotime() function and the DateTime constructor both take stacking relative values, and will process them in order, so you can do things like:

    $when = strtotime('now +1 year -1 weekdays');
    $when = new DateTime('now +1 year -1 weekdays');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search