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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16757728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:39:40  来源:igfitidea点击:

Creating new Date Time from string

php

提问by aherlambang

I have a string which is '23/05/2013' and I wanted to create a new Date Time object from this, so I did:

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

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

Any idea why I am getting this error all the time:

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

DateTime::__construct(): Failed to parse time string (23/05/2013) at position 0 (2): Unexpected character

回答by craig1231

According to http://www.php.net/manual/en/datetime.formats.date.php

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

It's mm/dd/yyyy, which is American, not British

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

Use

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

回答by Farkie

If you want to use the object normally rather than statically try this:

如果您想正常使用对象而不是静态使用对象,请尝试以下操作:

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

then you can use it like normal:

然后你可以像往常一样使用它:

echo $newDate->format('Y-m-d');