在 PHP 中轉換日期格式
使用者經常遇到在不同格式之間轉換日期的需要。在 PHP 中,將日期從 YYYY-MM-DD 轉換為 DD-MM-YYYY 會帶來挑戰,因為日期函數需要時間戳記。解決這個問題的方法如下:
使用strtotime() 和date() 函數
若不依賴SQL 轉換日期格式,可以使用strtotime( ) 和date() 函數。此方法涉及以下步驟:
$originalDate = "2010-03-21"; $newDate = date("d-m-Y", strtotime($originalDate)); // Output: 21-03-2010
替代方法:DateTime 類別
雖然上述解決方案對於簡單轉換非常有效,但複雜的日期操作需要更多穩健的方法。在這裡,DateTime 類別開始發揮作用:
$dt = new DateTime($originalDate); $newDateFormat = $dt->format("d-m-Y"); // Output: 21-03-2010
以上是如何在 PHP 中將 YYYY-MM-DD 轉換為 DD-MM-YYYY 日期格式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!