今天在做报表时用到了字符串与时间的相互转化,在此记录时间、时间戳、字符串三者的转化方式,以便日后查看。

#时间转字符串
mysql> select date_format(now(), '%Y-%m-%d');
+--------------------------------+
| date_format(now(), '%Y-%m-%d') |
+--------------------------------+
| 2020-07-22                     |
+--------------------------------+


#时间转时间戳
mysql> select unix_timestamp(now());
+-----------------------+
| unix_timestamp(now()) |
+-----------------------+
|            1595385579 |
+-----------------------+


#字符串转时间
mysql> select str_to_date('2020-07-22', '%Y-%m-%d %H');
+------------------------------------------+
| str_to_date('2020-07-22', '%Y-%m-%d %H') |
+------------------------------------------+
| 2020-07-22 00:00:00                      |
+------------------------------------------+


#字符串转时间戳
mysql> select unix_timestamp('2020-07-22');
+------------------------------+
| unix_timestamp('2020-07-22') |
+------------------------------+
|                   1595347200 |
+------------------------------+

#时间戳转时间
mysql> select from_unixtime(1595347200);
+---------------------------+
| from_unixtime(1595347200) |
+---------------------------+
| 2020-07-22 00:00:00       |
+---------------------------+


#时间戳转字符串
mysql> select from_unixtime(1595347200 ,'%Y-%m-%d');
+---------------------------------------+
| from_unixtime(1595347200 ,'%Y-%m-%d') |
+---------------------------------------+
| 2020-07-22                            |
+---------------------------------------+


又香又白人人夸