开发者

Change date to display correctly

开发者 https://www.devze.com 2023-02-24 10:14 出处:网络
There are many date posts here, but i don\'t see one that helps me. My mySQL field is in the format of yyyymmdd(example:20110423).

There are many date posts here, but i don't see one that helps me.

My mySQL field is in the format of yyyymmdd (example: 20110423).

I need to display it properly on the page like: 04/23/2011

How do I go about doing that? I pull the data fine int开发者_运维技巧o the page as 20110423, but don't know how to reformat it when displaying it. Any help is greatly appreciated!

Nick


echo date('r',strtotime('20110423'));

.. so in your case

echo date('m/d/Y',strtotime('20110423'));


date_format: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

SELECT DATE_FORMAT(date_field,'%d/%m/%Y') as date_out ...


$dt = \DateTime::createFromFormat('Ymd', '20110423');
echo $dt->format('m/d/Y');

The reason I like this better than strtotime() is that it can be picky about the date format given and you have no say over how it parses the string.

For example, given the date 12/10/2011 it will always parse this as "10th December, 2011". Change the slashes to hyphens 12-10-2011 and it becomes "12th October 2011".

Disclaimer: PHP 5.3+ only. As the 5.2 branch has ceased development and 5.3 has been around for almost two years, I don't see this as a problem.

Edit: If you don't have PHP 5.3 and the DB column is not a date type, you can use this extension on Dagon's answer

SELECT DATE_FORMAT(STR_TO_DATE(date_field, '%Y%m%d'), '%d/%m/%Y') AS date_field ...

See STR_TO_DATE().

0

精彩评论

暂无评论...
验证码 换一张
取 消