从字符串创建新的日期时间

问题描述 投票:0回答:2

我有一个字符串“23/05/2013”,我想从中创建一个新的日期时间对象,所以我这样做了:

new \DateTime('23/05/2013');

知道为什么我总是收到此错误吗:

DateTime::__construct(): Failed to parse time string (23/05/2013) at position 0 (2): Unexpected character
php
2个回答
72
投票

根据https://www.php.net/manual/en/datetime.formats.php#datetime.formats.date

是 mm/dd/yyyy,这是美国的,不是英国的

使用

DateTime::createFromFormat('d/m/Y', '23/05/2013');

41
投票

如果你想正常使用该对象而不是静态地尝试这个:

$datetime = new DateTime();
$newDate = $datetime->createFromFormat('d/m/Y', '23/05/2013');

然后你就可以像平常一样使用它了:

echo $newDate->format('Y-m-d');
© www.soinside.com 2019 - 2024. All rights reserved.