PHP Conference Japan 2024

DateTimeImmutable::modify

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

DateTimeImmutable::modify建立一個修改了時間戳記的新物件

說明

public DateTimeImmutable::modify(字串 $modifier): DateTimeImmutable

建立一個修改了時間戳記的新 DateTimeImmutable 物件。原始物件不會被修改。

參數

modifier

日期/時間字串。有效格式說明於 日期和時間格式

回傳值

成功時回傳 DateTimeImmutable。程序式風格在失敗時回傳 false

錯誤/例外

如果傳入無效的日期/時間字串,會拋出 DateMalformedStringException 例外。在 PHP 8.3 之前,這是一個警告。

更新日誌

版本 說明
8.3.0 如果傳入無效的字串,DateTimeImmutable::modify() 現在會拋出 DateMalformedStringException 例外。以前,它會返回 false,並發出警告。

範例

範例 #1 DateTimeImmutable::modify() 範例

物件導向風格

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

以上範例將輸出

2006-12-13

範例 #2 加或減月份時要注意

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

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

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

以上範例將輸出

2001-01-31
2001-03-03

參見

新增註記

使用者貢獻的註記

此頁面沒有使用者貢獻的註記。
To Top