【问题标题】:How to convert the date record wth DATE type in mysql database, [duplicate]如何在mysql数据库中转换日期类型的日期记录,[重复]
【发布时间】:2020-08-10 19:05:15
【问题描述】:

老实说,我只是一个使用 PHP 和 Mysql 编码的新手。 我只想知道是否有人可以帮助我如何将 mysql 数据库表中的日期记录转换为“DATE”类型。目前,我可以显示默认格式(yyyy-mm-dd)。但我想将其显示为“Jan-20-2020”。

这是我已经完成的显示默认格式的代码部分。 https://www.screencast.com/t/WOou3TAsT 请帮助我应该添加什么代码来转换并以字符格式显示,如上面的示例。

这是我正在显示的当前结果; https://www.screencast.com/t/zcWp8sZ34

感谢阅读并感谢任何帮助。

问候, 梅洛维拉纽瓦

【问题讨论】:

标签: php mysql date formatting


【解决方案1】:

由于您使用的是 mySQL 数据库,请尝试以下操作:

使用 MySQL 中的 STR_TO_DATE() 方法进行转换。语法如下,其中我们使用格式说明符。格式说明符以 % 开头。

SELECT STR_TO_DATE(yourDateColumnName,'%d.%m.%Y') as anyVariableName FROM yourTableName;

为了理解上面的语法,让我们创建一个表。创建表的查询如下。

mysql> create table ConvertIntoDateFormat
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> LoginDate varchar(30),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.47 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into ConvertIntoDateFormat(LoginDate) values('11.01.2019');
Query OK, 1 row affected (0.10 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('10.04.2017');
Query OK, 1 row affected (0.16 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('21.10.2016');
Query OK, 1 row affected (0.12 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('26.09.2018');
Query OK, 1 row affected (0.14 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('25.12.2012');
Query OK, 1 row affected (0.17 sec)

使用 select 语句显示表中的所有记录。查询如下——

mysql> select *from ConvertIntoDateFormat;

以下是输出。

+----+------------+
| Id | LoginDate  |
+----+------------+
|  1 | 11.01.2019 |
|  2 | 10.04.2017 |
|  3 | 21.10.2016 |
|  4 | 26.09.2018 |
|  5 | 25.12.2012 |
+----+------------+
5 rows in set (0.00 sec)

以下是将日期格式化为 YYYY-MM-DD 的查询。

mysql> select str_to_date(LoginDate,'%d.%m.%Y') as DateFormat from ConvertIntoDateFormat;
Here is the output.

+------------+
| DateFormat |
+------------+
| 2019-01-11 |
| 2017-04-10 |
| 2016-10-21 |
| 2018-09-26 |
| 2012-12-25 |
+------------+

5 行(0.00 秒) 您也可以将 DATE_FORMAT() 方法用于相同目的。查询如下

mysql> select DATE_FORMAT(STR_TO_DATE(LoginDate,'%d.%m.%Y'), '%Y-%m-%d') as DateFormat from
   -> ConvertIntoDateFormat;

以下是输出-

+------------+
| DateFormat |
+------------+
| 2019-01-11 |
| 2017-04-10 |
| 2016-10-21 |
| 2018-09-26 |
| 2012-12-25 |
+------------+

集合中的 5 行(0.00 秒)

选自:https://www.tutorialspoint.com/mysql-date-format-to-convert-dd-mm-yy-to-yyyy-mm-dd

【讨论】:

  • 这是从前到后的。 OP 正在使用 DATE 数据类型
【解决方案2】:

echo date('M-m-Y', strtotime('2019-01-01'));会解决你的问题,你可以查看手册:datestrtotime,以获得完整的解释。

【讨论】:

    猜你喜欢
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 2021-10-28
    相关资源
    最近更新 更多