将日期从 YYYYMMDD 转换为 PHP 中的 DD/MM/YYYY 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14045027/
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
Convert date from YYYYMMDD to DD/MM/YYYY format in PHP
提问by rahules
I've a MySQL database table in which the date is stored in YYYYMMDD format. Eg: 20121226.
我有一个 MySQL 数据库表,其中日期以 YYYYMMDD 格式存储。例如:20121226。
I want to display this date in DD/MM/YYYY format. Eg: 26/12/2012
我想以 DD/MM/YYYY 格式显示此日期。例如:26/12/2012
What I came up with is to use substrto extract the day, month and year separately.
I would like to know if there's an easier way to do this.
我想出的是用来substr分别提取日、月和年。我想知道是否有更简单的方法来做到这一点。
Also, is there a way to convert this date to "26 December 2012" format without the need to write separate code?
另外,有没有办法将此日期转换为“2012 年 12 月 26 日”格式而无需编写单独的代码?
回答by jeremy
You can easily use the DateTime class to do this
您可以轻松地使用 DateTime 类来执行此操作
$retrieved = '20121226';
$date = DateTime::createFromFormat('Ymd', $retrieved);
echo $date->format('d/m/Y');
回答by leepowers
In your SQL statement you can format the date differently.
在您的 SQL 语句中,您可以以不同的方式格式化日期。
SELECT DATE_FORMAT(date_column, '%d/%m/%Y') AS my_date FROM my_table
回答by Mehdi Karamosly
This is the solution :
这是解决方案:
SELECT DATE_FORMAT('20121226', '%d/%m/%Y');
SELECT DATE_FORMAT('20121226', '%d/%m/%Y');
=>
=>
DATE_FORMAT('20121226', '%d/%m/%Y')
26/12/2012
OR
或者
SELECT DATE_FORMAT('20121226', '%W %M %Y');
SELECT DATE_FORMAT('20121226', '%W %M %Y');
=>
=>
DATE_FORMAT('20121226', '%W %M %Y')
Wednesday December 2012
Check this for more formatting: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
检查更多格式:http: //dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

