Home > Net >  How to add a year to today's date and default it to the preceding working day
How to add a year to today's date and default it to the preceding working day

Time:12-02

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.

CodePudding user response:

I found the answer:

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

CodePudding user response:

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
  •  Tags:  
  • php
  • Related