PHP Conference Japan 2024

DateTimeImmutable::__construct

date_create_immutable

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

DateTimeImmutable::__construct -- date_create_immutable返回新的 DateTimeImmutable 物件

說明

物件導向風格

public DateTimeImmutable::__construct(字串 $datetime = "now", ?DateTimeZone $timezone = null)

程序式風格

返回一個新的 DateTimeImmutable 物件。

參數

datetime

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

當使用 $timezone 參數時,在此輸入 "now" 以取得目前時間。

timezone

一個代表 $datetime 時區的 DateTimeZone 物件。

如果省略 $timezone 或其值為 null,則會使用目前的時區。

注意事項:

$datetime 參數是 UNIX 時間戳記(例如 @946684800)或指定了時區(例如 2010-01-28T15:00:00+02:002010-07-05T06:00:00Z)時,$timezone 參數和目前的時區將會被忽略。

回傳值

返回一個新的 DateTimeImmutable 實例。

錯誤/例外

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

更新日誌

版本 說明
8.3.0 現在如果傳入無效的字串,會拋出 DateMalformedStringException 例外,而不是 Exception
7.1.0 現在微秒會填入實際值,而不是 '00000'。

範例

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

物件導向風格

<?php
try {
$date = new DateTimeImmutable('2000-01-01');
} catch (
Exception $e) {
echo
$e->getMessage();
exit(
1);
}

echo
$date->format('Y-m-d');
?>

程序式風格

<?php
$date
= date_create('2000-01-01');
if (!
$date) {
$e = date_get_last_errors();
foreach (
$e['errors'] as $error) {
echo
"$error\n";
}
exit(
1);
}

echo
date_format($date, 'Y-m-d');
?>

上述範例會輸出

2000-01-01

範例 #2 DateTimeImmutable::__construct() 的一些細節

<?php
// 指定您電腦時區中的日期/時間。
$date = new DateTimeImmutable('2000-01-01');
echo
$date->format('Y-m-d H:i:sP') . "\n";

// 指定時區中的指定日期/時間。
$date = new DateTimeImmutable('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo
$date->format('Y-m-d H:i:sP') . "\n";

// 您電腦時區中的目前日期/時間。
$date = new DateTimeImmutable();
echo
$date->format('Y-m-d H:i:sP') . "\n";

// 指定時區中的目前日期/時間。
$date = new DateTimeImmutable('now', new DateTimeZone('Pacific/Nauru'));
echo
$date->format('Y-m-d H:i:sP') . "\n";

// 使用 UNIX 時間戳記。請注意,結果位於 UTC 時區。
$date = new DateTimeImmutable('@946684800');
echo
$date->format('Y-m-d H:i:sP') . "\n";

// 不存在的值會滾動。
$date = new DateTimeImmutable('2000-02-30');
echo
$date->format('Y-m-d H:i:sP') . "\n";
?>

以上範例的輸出結果類似於

2000-01-01 00:00:00-05:00
2000-01-01 00:00:00+12:00
2010-04-24 10:24:16-04:00
2010-04-25 02:24:16+12:00
2000-01-01 00:00:00+00:00
2000-03-01 00:00:00-05:00

範例 #3 變更關聯的時區

<?php
$timeZone
= new \DateTimeZone('Asia/Tokyo');

$time = new \DateTimeImmutable();
$time = $time->setTimezone($timeZone);

echo
$time->format('Y/m/d H:i:s'), "\n";
?>

以上範例的輸出結果類似於

2022/08/12 23:49:23

範例 #4 使用相對日期/時間字串

<?php
$time
= new \DateTimeImmutable("-1 year");

echo
$time->format('Y/m/d H:i:s'), "\n";
?>

以上範例的輸出結果類似於

2021/08/12 15:43:51
新增註解

使用者貢獻的註解 1 則註解

Dmitrii
1 年前
「如果省略 $timezone 或其值為 null,則會使用目前的時區。」 - 請注意,時區不等於偏移量,如果這對您的應用程式很重要。

如果預設時區 = Europe/Moscow,則
echo (new \DateTimeImmutable('2014-10'))->format(DATE_ATOM); // 輸出 "2014-10-01T00:00:00+04:00"
echo (new \DateTimeImmutable('2014-11'))->format(DATE_ATOM); // 輸出 "2014-11-01T00:00:00+03:00"
因為法律變更(廢除「夏令時間」)。
To Top