如何在 PHP 中將一種日期格式轉換為另一種日期格式
Minahil Noor
2023年1月30日
PHP
PHP Date
-
在 PHP 中使用
date()和strtotime()函式將一種日期格式轉換為另一種日期格式 -
在 PHP 中使用
createFromFormat()和format()函式將一種日期格式轉換為另一種日期格式
在本文中,我們將介紹在 PHP 中將一種日期格式轉換為另一種格式的方法。
- 使用
date()和strtotime()函式 - 使用
createFromFormat()和format()函式
在 PHP 中使用 date() 和 strtotime() 函式將一種日期格式轉換為另一種日期格式
date() 函式將時間戳轉換為日期 date。使用此函式的正確語法如下
date( $format, $timestamp);
$format 是轉換日期的特定格式。
$timestamp 是一個可選引數。它根據傳遞的時間戳給出日期。如果省略的話,那麼我們將獲得當前的日期。
函式 strtotime() 是 PHP 中的內建函式。此函式將日期轉換為時間。使用此函式的正確語法如下。
strtotime($dateString, $timeNow);
$dateString 是必需引數,它是日期的字串表示形式。
$timeNow 是一個可選引數。它是用於計算相對日期的時間戳。
<?php
$originalDate = "2020-04-29";
//original date is in format YYYY-mm-dd
$timestamp = strtotime($originalDate);
$newDate = date("m-d-Y", $timestamp );
echo "The new date is $newDate.";
?>
我們使用了 date() 和 strtotime() 函式將一種日期格式轉換為另一種格式。函式 strtotime() 已將原始日期轉換為時間戳。然後使用 date() 函式將該時間戳轉換為所需格式的日期。
輸出:
The new date is 04-29-2020.
在 PHP 中使用 createFromFormat() 和 format() 函式將一種日期格式轉換為另一種日期格式
函式 createFromFormat() 是 PHP 中的內建函式。該函式將時間戳或日期字串轉換為 DateTime 物件。使用此函式的正確語法如下。
DateTime::createFromFormat($format, $time, $timezone);
變數 $format 是日期的格式,$time 是時間或字串中的日期,$timezone 是時區。前兩個引數是必需引數。
format() 函式用於將 date 格式化為所需格式。使用此函式的正確語法是
$datetimeObject->format($formatString);
引數 $formatString 指定所需的格式。
<?php
$originalDate = "2020-04-29";
//original date is in format YYYY-mm-dd
$DateTime = DateTime::createFromFormat('Y-m-d', $originalDate);
$newDate = $DateTime->format('m-d-Y');
echo "The new date is $newDate.";
?>
在這裡,我們使用 createFromFormat() 函式建立了一個 DateTime 物件。然後,DateTime 物件呼叫 format() 函式將一種日期格式轉換為另一種。
輸出:
The new date is 04-29-2020.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe