更改从 mysql 检索的 php 中的日期格式

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

Change date format in php retrieved from mysql

phpmysql

提问by Namit

I have a column in mysql which stores the dates. So in mysql the dates are stored in Y-M-Dformat. However on retrieval i want to view change that format to D-M-Y. I read online at a few places and i found the date() in php, Date conversion. But they are generally for timestamp, also in many cases people had recommended to split the variable by -and then changing position.

我在 mysql 中有一个列存储日期。所以在 mysql 中,日期以Y-M-D格式存储。但是在检索时我想查看将该格式更改为D-M-Y. 我在几个地方在线阅读,我在 php 中找到了 date(),Date conversion。但它们通常用于时间戳,在许多情况下人们也建议通过-然后改变位置来分割变量。

My question is that, is splitting the variable the only option here or do we have any built in function that does that for us?

我的问题是,拆分变量是这里唯一的选择,还是我们有任何内置函数可以为我们做到这一点?

回答by Saket Patel

this should work for you, check here http://codepad.org/YdZQzgXR

这应该适合你,在这里查看http://codepad.org/YdZQzgXR

<?
   $date = '2012-12-30';
   echo date('d-m-Y', strtotime($date));
?>

回答by KARASZI István

You can do that on the PHP side or on the MySQL side.

您可以在 PHP 端或 MySQL 端执行此操作。

On the MySQL side you could use DATE_FORMAT:

在 MySQL 方面,您可以使用DATE_FORMAT

SELECT DATE_FORMAT(NOW(), '%d-%m-%Y');

or from a field:

或从一个领域:

SELECT id, DATE_FORMAT(created_at, '%d-%m-%Y') FROM articles;

On the PHP side you have more tools:

在 PHP 方面,您有更多工具:

  • use a database abstraction layer (PDO, MDB, etc.)
  • parse the returned time with strptimeand then use strftimeto format it
  • split as you mentioned
  • ...
  • 使用数据库抽象层(PDO、MDB 等)
  • 解析返回的时间,strptime然后使用strftime它来格式化它
  • 正如你所说的分开
  • ...

回答by Niko

Two possibilities: PHP's strtotime() or let MySQL do the job!

两种可能性:PHP 的 strtotime() 或让 MySQL 来完成这项工作!