使用 MySQL SELECT 將 DATETIME 格式設定為“DDMM- YYYY HH:MM:SS” ?
每當您從表中檢索 datetime 時,datetime 都會採用“YYYY-MM-DD”格式。如果您想更改輸出,則需要使用 MySQL 中的內建 date_format()。
語法如下 -
SELECT DATE_FORMAT(yourDatetimeColumnName,yourFormat) as anyVariableName from yourTableName;
為了理解以上語法,我們首先建立一個表。建立表所需的查詢如下 -
mysql> create table UserDateFormat -> ( -> ProductId int, -> ProductDeliverDate datetime -> ); Query OK, 0 rows affected (0.93 sec)
使用 insert 命令在表中插入一些記錄。查詢如下 -
mysql> insert into UserDateFormat values(100,date_add(now(),interval 1 year)); Query OK, 1 row affected (0.10 sec) mysql> insert into UserDateFormat values(101,date_add(now(),interval -1 year)); Query OK, 1 row affected (0.48 sec) mysql> insert into UserDateFormat values(102,date_add(now(),interval -3 year)); Query OK, 1 row affected (0.17 sec) mysql> insert into UserDateFormat values(103,date_add(now(),interval -2 year)); Query OK, 1 row affected (0.20 sec)
使用 select 命令顯示錶中的所有記錄。查詢如下 -
mysql> select *from UserDateFormat;
輸出
+-----------+---------------------+ | ProductId | ProductDeliverDate | +-----------+---------------------+ | 100 | 2019-12-24 13:32:47 | | 101 | 2017-12-24 13:32:58 | | 102 | 2015-12-24 13:33:08 | | 103 | 2016-12-24 13:33:17 | +-----------+---------------------+ 4 rows in set (0.00 sec)
以上 datetime 格式來自 MySQL datetime。現在您可以相應地設定 datetime 格式,其中還包括“DD-MM-YYYY”格式。
查詢如下 -
mysql> select date_format(ProductDeliverDate,'%d-%m-%Y %h:%i:%s') as UserFormat from UserDateFormat;
以下是顯示 DD-MM-YYYY 格式日期的輸出 -
+----------------------+ | UserFormat | +----------------------+ | 24-12-2019 01:32:47 | | 24-12-2017 01:32:58 | | 24-12-2015 01:33:08 | | 24-12-2016 01:33:17 | +----------------------+ 4 rows in set (0.00 sec)
您可以以 24 小時格式獲取以上時間格式。查詢如下 -
mysql> select date_format(ProductDeliverDate,'%d-%m-%Y %H:%i:%S') as UserFormat from UserDateFormat;
輸出
+----------------------+ | UserFormat | +----------------------+ | 24-12-2019 13:32:47 | | 24-12-2017 13:32:58 | | 24-12-2015 13:33:08 | | 24-12-2016 13:33:17 | +----------------------+ 4 rows in set (0.00 sec)
廣告