将日期格式(以DB或输出)更改为dd / mm / yyyy - PHP MySQL [英] Change date format (in DB or output) to dd/mm/yyyy - PHP MySQL

查看:113
本文介绍了将日期格式(以DB或输出)更改为dd / mm / yyyy - PHP MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MySQL存储日期在我的数据库(默认情况下)为'YYYY-MM-DD'我的日期的字段类型是'DATE'(我不需要任何时间存储)..有一个简单的方法来改变它默认为DD / MM / YYYY?



我在两个不同的表中调用不同的日期,我的任何代码中没有哪个类似日期变量或任何东西!希望这是一个直接的变化?

解决方案

在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 类,特别是:





例如,这部分代码:

  $ 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 :

  • Transform the date to a timestamp, using strtotime
  • Format it, using date

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 :

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆