PHPCon Poland 2024

DateTime::modify

date_modify

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::modify -- date_modify修改日期时间对象的值

说明

面向对象风格

public DateTime::modify(string $modifier): DateTime|false

过程化风格

通过 DateTimeImmutable::__construct() 能够接受的格式,对 Datetime 对象的时间戳进行修改(自增或者自减)。

参数

object

仅过程化风格:由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。

modifier

日期/时间字符串。正确格式的说明详见 日期与时间格式

返回值

返回方法链修改后的 DateTime 对象, 或者在失败时返回 false

错误/异常

仅限于面向对象的 API:如果传递了无效的日期/时间字符串,将抛出 DateMalformedStringException

更新日志

版本 说明
8.3.0 现在如果传递了无效的字符串,DateTime::modify() 将抛出 DateMalformedStringException 而不是警告。date_modify() 尚未更改。

示例

示例 #1 DateTime::modify() 示例

面向对象风格

<?php
$date
= new DateTime('2006-12-12');
$date->modify('+1 day');
echo
$date->format('Y-m-d');
?>

过程化风格

<?php
$date
= date_create('2006-12-12');
date_modify($date, '+1 day');
echo
date_format($date, 'Y-m-d');
?>

以上示例会输出:

2006-12-13

示例 #2 增加或者减少月份的时候需要当心

<?php
$date
= new DateTime('2000-12-31');

$date->modify('+1 month');
echo
$date->format('Y-m-d') . "\n";

$date->modify('+1 month');
echo
$date->format('Y-m-d') . "\n";
?>

以上示例会输出:

2001-01-31
2001-03-03

示例 #3 支持所有日期和时间格式

<?php
$date
= new DateTime('2020-12-31');

$date->modify('July 1st, 2023');
echo
$date->format('Y-m-d H:i') . "\n";

$date->modify('Monday next week');
echo
$date->format('Y-m-d H:i') . "\n";

$date->modify('17:30');
echo
$date->format('Y-m-d H:i') . "\n";
?>

以上示例会输出:

2023-07-01 00:00
2023-07-03 00:00
2023-07-03 17:30

参见

add a note

User Contributed Notes 1 note

up
1
php_net at striderweb dot com
1 month ago
You have to be a bit careful with variables here. If for example you want to add a variable amount of minutes you might use `->modify("+$min"). This will not work out if `$min` is a negative number, because modify will see the "+" and ignore the "-". If `$min` equals -10, modify in this example will add ten minutes, not subtract!

What is happening is if the modify string has two operations, the first will be obeyed and later ones will be ignored.

So "+-10 minutes" will add ten minutes, even though you might expect it to add the negative number. Similarly "--10 minutes" will subtract ten minutes, despite the apparent logic of subtracting a negative number.
To Top