📜  PHP | DateTimeImmutable modify()函数(1)

📅  最后修改于: 2023-12-03 15:03:36.549000             🧑  作者: Mango

PHP | DateTimeImmutable modify()函数

在PHP中,DateTimeImmutable是一个不可变的日期时间对象。它提供了许多方法来处理日期和时间。其中之一是modify()函数,它允许我们通过在原日期时间基础上进行修改来创建一个新的日期时间对象。

语法
public DateTimeImmutable DateTimeImmutable::modify (string $modifier)

其中,modifier参数是一个修改字符串,它可以包含各种日期时间修改命令。

修改命令示例

| 命令 | 描述 | | --- | --- | | +5 days | 增加5天 | | -1 month | 减少1个月 | | next Tuesday | 下一个星期二 | | last day of next month | 下个月的最后一天 | | first day of +1 year | 下一年的第一天 |

代码示例

下面的代码演示如何使用modify()函数。我们首先创建了一个DateTimeImmutable对象,然后使用modify()函数进行各种修改。

$date = new DateTimeImmutable('2021-11-15');

$newDate1 = $date->modify('+1 day');
echo $newDate1->format('Y-m-d'); // 输出:2021-11-16

$newDate2 = $date->modify('-1 month');
echo $newDate2->format('Y-m-d'); // 输出:2021-10-15

$newDate3 = $date->modify('next Tuesday');
echo $newDate3->format('Y-m-d'); // 输出:2021-11-16

$newDate4 = $date->modify('last day of next month');
echo $newDate4->format('Y-m-d'); // 输出:2021-12-31

$newDate5 = $date->modify('first day of +1 year');
echo $newDate5->format('Y-m-d'); // 输出:2022-01-01
注意事项

由于DateTimeImmutable是一个不可变的对象,modify()函数不会直接修改原对象,而是返回一个新的DateTimeImmutable对象。因此,在使用modify()函数时,请确保在需要的时候将修改后的日期时间对象存储在新变量中。