使用 DateTimeImmutable 类。
$date = new DateTimeImmutable(
'2019-05-13',
new DateTimezone('America/Los_Angeles')
);
现在您可以使用format() 方法以特定格式输出日期:
var_dump($date->format('m/d/Y'));
string(10) "05/13/2019"
您可能想知道为什么我提供了时区。好吧,试试以下方法:
// full date time in iso format
var_dump(
$date->format(DateTimeInterface::RFC3339)
);
// with a different timezone
var_dump(
$date
->setTimezone(new DateTimezone('America/Atka'))
->format(DateTimeInterface::RFC3339)
);
string(25) "2019-05-13T00:00:00-07:00"
string(25) "2019-05-12T22:00:00-09:00"
完整的日期时间需要完整的时区。
另一种格式化日期时间的方法是使用IntlDateFormatter。它允许您使用语言环境设置日期格式,从而更轻松地开发多种语言。
var_dump(
[
'en-US'=> IntlDateFormatter::formatObject(
$date, [IntlDateFormatter::SHORT, IntlDateFormatter::NONE], 'en-US'
),
'en-GB'=> IntlDateFormatter::formatObject(
$date, [IntlDateFormatter::SHORT, IntlDateFormatter::NONE], 'en-GB'
),
'de-DE'=> IntlDateFormatter::formatObject(
$date, [IntlDateFormatter::SHORT, IntlDateFormatter::NONE], 'de-DE'
),
'ar-AE'=> IntlDateFormatter::formatObject(
$date, [IntlDateFormatter::SHORT, IntlDateFormatter::NONE], 'ar-AE'
),
]
);
array(3) {
["en-US"]=>
string(7) "5/13/19"
["en-GB"]=>
string(10) "13/05/2019"
["de-DE"]=>
string(8) "13.05.19"
["ar-AE"]=>
string(22) "١٣/٥/٢٠١٩"
}