如何在 PHP 中解析日期字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2767324/
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 07:38:08  来源:igfitidea点击:

How to parse a date string in PHP?

phpdateparsing

提问by user295515

With a date string of Apr 30, 2010, how can I parse the string into 2010-04-30using PHP?

使用日期字符串Apr 30, 2010,如何将字符串解析为2010-04-30使用 PHP?

采纳答案by zaf

Try http://php.net/manual/en/function.strtotime.phpto convert to a timestamp and then http://www.php.net/manual/en/function.date.phpto get it in your own format.

尝试http://php.net/manual/en/function.strtotime.php转换为时间戳,然后http://www.php.net/manual/en/function.date.php将其转换为您自己的格式。

回答by Gordon

Either with the DateTime API (requires PHP 5.3+):

使用 DateTime API(需要 PHP 5.3+):

$dateTime = DateTime::createFromFormat('F d, Y', 'Apr 30, 2010');
echo $dateTime->format('Y-m-d');

or the same in procedural style (requires PHP 5.3+):

或程序风格相同(需要 PHP 5.3+):

$dateTime = date_create_from_format('F d, Y', 'Apr 30, 2010');
echo date_format($dateTime, 'Y-m-d');

or classic (requires PHP4+):

或经典(需要 PHP4+):

$dateTime = strtotime('Apr 30, 2010');
echo date('Y-m-d', $dateTime);