本文整理mysql常用的时间函数,针对日期、时间戳、字符串类型之间的转换操作。

获得当前日期时间

函数:now(),返回当前时间,类型datetime

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2020-11-15 14:57:14 |
+---------------------+

获得当前时间戳函数

函数:current_timestamp()

mysql> select current_timestamp;
+---------------------+
| current_timestamp   |
+---------------------+
| 2020-11-15 14:58:05 |
+---------------------+

日期时间转为字符串

函数:date_format(date,format), time_format(time,format)

mysql> select date_format('2008-08-08 22:23:01', '%Y%m%d%H%i%s');
+----------------------------------------------------+
| date_format('2008-08-08 22:23:01', '%Y%m%d%H%i%s') |
+----------------------------------------------------+
| 20080808222301                                     |
+----------------------------------------------------+

mysql> select gmt_create, date_format(gmt_create, '%Y%m%d%H%i%s') from op_log_info limit 2;
+---------------------+-----------------------------------------+
| gmt_create          | date_format(gmt_create, '%Y%m%d%H%i%s') |
+---------------------+-----------------------------------------+
| 2020-06-20 11:29:48 | 20200620112948                          |
| 2020-06-20 11:38:51 | 20200620113851                          |
+---------------------+-----------------------------------------+

字符串转为时间

函数:str_to_date(str, format)

mysql> select str_to_date('08/09/2008', '%m/%d/%Y');
+---------------------------------------+
| str_to_date('08/09/2008', '%m/%d/%Y') |
+---------------------------------------+
| 2008-08-09                            |
+---------------------------------------+

mysql> select str_to_date('08.09.2008 08:09:30', '%m.%d.%Y %h:%i:%s'); -- 2008-08-09 08:09:30
+---------------------------------------------------------+
| str_to_date('08.09.2008 08:09:30', '%m.%d.%Y %h:%i:%s') |
+---------------------------------------------------------+
| 2008-08-09 08:09:30                                     |
+---------------------------------------------------------+

时间戳转换为datetime

mysql> select from_unixtime(unix_timestamp('2020-11-13 20:03:58'));
+------------------------------------------------------+
| from_unixtime(unix_timestamp('2020-11-13 20:03:58')) |
+------------------------------------------------------+
| 2020-11-13 20:03:58                                  |
+------------------------------------------------------+

参考