我有一個 DateTime 格式的字串,'2022-03-17T15:00:00 02:00'我需要一個 php 函式來只回傳 Date '2022-03-17'。我沒有找到解決辦法。該字串'2022-03-17T15:00:00 02:00'在 xml 提要中是可變的。它每天都在變化,因此必須格式化以包含在函式中。
uj5u.com熱心網友回復:
我很確定我已經看到這個問題很多時間了。做一些適當的搜索,但與此同時。用這個:
$date = '2022-03-17T15:00:00 02:00';
var_dump(date('Y-m-d',strtotime($date))); //output: 2022-03-17
uj5u.com熱心網友回復:
store your date time in a variable and try this:
$date_to_be_formatted = '2022-03-17T15:00:00 02:00';
echo get_date($date_to_be_formatted);
function get_date($data_to_be_formatted){
$formatted_date = date('Y-m-d',strtotime($date));
return $formatted_date;
}
output:
2022-03-17
uj5u.com熱心網友回復:
strtotime 不適合與 date 一起轉換包含時區的日期,例如此處的 02:00。與其他時區有關的錯誤可能會發生。例子:
date_default_timezone_set('America/New_York');
$time = '2022-03-17T01:00:00 02:00';
echo date("Y-m-d", strtotime($time));
//2022-03-16
自己看!
這里通常建議使用 DateTime,因為時區處理正確。
date_default_timezone_set('America/New_York');
$time = '2022-03-17T01:00:00 02:00';
echo date_create($time)->format('Y-m-d');
//2022-03-17
uj5u.com熱心網友回復:
echo date("Y-m-d", strtotime($time));
https://www.php.net/manual/en/function.date.php
uj5u.com熱心網友回復:
@Denis 和 @Relcode
該功能現在可以正常作業:
function get_date( $time ) {
$time = '2022-03-17T15:00:00 02:00';
echo date("Y-m-d", strtotime($time));
}
echo get_date('2022-03-17T15:00:00 02:00');
輸出:2022-03-17
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/444048.html
