php 如何将年份添加到今天的日期并将其默认为前一个工作日

sqyvllje  于 2022-12-02  发布在  PHP
关注(0)|答案(2)|浏览(132)

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.

x8diyxa7

x8diyxa71#

我找到了答案:

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

qpgpyjmq2#

您只需要在今天的日期上加上一年,然后检查星期几,如果是“星期六”或“星期日”,则减去一个工作日。The PHP DateTime object通过format()modify()方法使这一操作变得简单。

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

在所有这些情况下:

  • 今日(2022年12月1日,星期四)
  • 明天(2022年12月2日,星期五)
  • 次日(2022年12月3日星期六)

上面将输出:

Fri, 01/12/2023

相关问题