PHP函式名:DateTimeImmutable::setTimestamp()
適用版本:5.5及以上版本
用法:
DateTimeImmutable::setTimestamp()
函式用於設定一個 DateTimeImmutable 物件的時間戳。時間戳是一個表示日期和時間的整數值。
函式語法:
DateTimeImmutable DateTimeImmutable::setTimestamp(int $timestamp)
引數說明:
- $timestamp: 必需。一個整數值,表示日期和時間的時間戳。
返回值:
- 返回一個新的 DateTimeImmutable 物件。
示例:
$timestamp = strtotime("2021-01-01 00:00:00"); // 獲取時間戳
$date = new DateTimeImmutable(); // 建立一個新的 DateTimeImmutable 物件
$date = $date->setTimestamp($timestamp); // 設定時間戳
echo $date->format('Y-m-d H:i:s'); // 輸出:2021-01-01 00:00:00
在上述示例中,我們首先使用 strtotime()
函式將日期時間字串轉換為時間戳。然後,我們建立了一個新的 DateTimeImmutable 物件,將其時間戳設定為之前獲取的時間戳。最後,使用 format()
方法將日期時間格式化為我們想要的格式進行顯示。
值得注意的是,DateTimeImmutable物件是不可變的,它的 setTimestamp()
方法會返回一個新的DateTimeImmutable物件,而不是修改原始物件。