将日期格式(以DB或输出)更改为dd / mm / yyyy - PHP MySQL [英] Change date format (in DB or output) to dd/mm/yyyy - PHP MySQL
问题描述
我在两个不同的表中调用不同的日期,我的任何代码中没有哪个类似日期变量或任何东西!希望这是一个直接的变化?
在PHP中,您可以:
有点像这样,我会说:
$ timestamp = strtotime($ date_from_db);
echo date('d / m / Y',$ timestamp);
但这只适用于1970年至2038年之间的日期,因为时间戳存储为32位整数,从1970-01-01开始计数。
在MySQL中,我认为 date_format
功能会做的。
例如:
mysql>选择date_format(curdate(),'%d /%m /%Y');
+ ------------------------------------ +
| date_format(curdate(),'%d /%m /%Y')|
+ ------------------------------------ +
| 19/03/2010 |
+ ------------------------------------ +
1行集(0.03秒)
为了完整性,另一个解决方案在PHP中,没有受到1970-2038的限制,将使用 DateTime
类,特别是:
-
DateTime :: __构造
来解析DB返回的日期 -
DateTime :: format
将日期格式化为任何您想要的格式。
例如,这部分代码:
$ date = new DateTime('2010-03-19');
echo $ date-> format('d / m / Y');
将得到您的输出:
19/03/2010
MySQL stores the date in my database (by default) as 'YYYY-MM-DD' The field type for my date is 'DATE' (I do not need any time storage).. Is there a simple way to change it by default to DD/MM/YYYY ?
I call up different dates in 2 different tables, and no where in any of my code do I have anything resembling a date variable or anything! Hopefully this is a straight forward change?
In PHP, you could :
A bit like this, I'd say :
$timestamp = strtotime($date_from_db);
echo date('d/m/Y', $timestamp);
But this will only work for dates between 1970 and 2038, as timestamps are stored as 32 bits integers, counting from 1970-01-01.
In MySQL, I suppose the date_format
function would do the trick.
For example :
mysql> select date_format(curdate(), '%d/%m/%Y');
+------------------------------------+
| date_format(curdate(), '%d/%m/%Y') |
+------------------------------------+
| 19/03/2010 |
+------------------------------------+
1 row in set (0.03 sec)
And, for the sake of completness, another solution, in PHP, that doesn't suffer from the limitation of 1970-2038 would be to use the DateTime
class, and, especially :
DateTime::__construct
to parse the date returned by the DBDateTime::format
to format the date to whatever format you want.
For example, this portion of code :
$date = new DateTime('2010-03-19');
echo $date->format('d/m/Y');
would get you this output :
19/03/2010
这篇关于将日期格式(以DB或输出)更改为dd / mm / yyyy - PHP MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!