一、MySQL中如何表示當(dāng)前時間?
其實,表達方式還是蠻多的,匯總?cè)缦拢?/p>
CURRENT_TIMESTAMP
CURRENT_TIMESTAMP()
NOW()
LOCALTIME
LOCALTIME()
LOCALTIMESTAMP
LOCALTIMESTAMP()
二、關(guān)于TIMESTAMP和DATETIME的比較
一個完整的日期格式如下:YYYY-MM-DD HH:MM:SS[.fraction],它可分為兩部分:date部分和time部分,其中,date部分對應(yīng)格式中的“YYYY-MM-DD”,time部分對應(yīng)格式中的“HH:MM:SS[.fraction]”。對于date字段來說,它只支持date部分,如果插入了time部分的內(nèi)容,它會丟棄掉該部分的內(nèi)容,并提示一個warning。
如下所示:
mysql> create table test(id int,hiredate date);Query OK, 0 rows affected (0.01 sec)mysql> insert into test values(1,'20151208000000');Query OK, 1 row affected (0.00 sec)mysql> insert into test values(1,'20151208104400');Query OK, 1 row affected, 1 warning (0.01 sec)mysql> show warning;ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'warning' at line 1mysql> select * from test;+------+------------+| id | hiredate |+------+------------+| 1 | 2015-12-08 || 1 | 2015-12-08 |+------+------------+2 rows in set (0.00 sec)
注:第一個沒提示warning的原因在于它的time部分都是0
TIMESTAMP和DATETIME的相同點:
1> 兩者都可用來表示YYYY-MM-DD HH:MM:SS[.fraction]類型的日期。
TIMESTAMP和DATETIME的不同點:
1> 兩者的存儲方式不一樣
對于TIMESTAMP,它把客戶端插入的時間從當(dāng)前時區(qū)轉(zhuǎn)化為UTC(世界標準時間)進行存儲。查詢時,將其又轉(zhuǎn)化為客戶端當(dāng)前時區(qū)進行返回。
而對于DATETIME,不做任何改變,基本上是原樣輸入和輸出。
下面,我們來驗證一下
首先創(chuàng)建兩種測試表,一個使用timestamp格式,一個使用datetime格式。
mysql> create table test(id int,hiredate timestamp);Query OK, 0 rows affected (0.01 sec)mysql> insert into test values(1,'20151208000000');Query OK, 1 row affected (0.00 sec)mysql> create table test1(id int,hiredate datetime);Query OK, 0 rows affected (0.01 sec)mysql> insert into test1 values(1,'20151208000000');Query OK, 1 row affected (0.00 sec)mysql> select * from test;+------+---------------------+| id | hiredate |+------+---------------------+| 1 | 2015-12-08 00:00:00 |+------+---------------------+1 row in set (0.01 sec)mysql> select * from test1;+------+---------------------+| id | hiredate |+------+---------------------+| 1 | 2015-12-08 00:00:00 |+------+---------------------+1 row in set (0.00 sec)
兩者輸出是一樣的。
其次修改當(dāng)前會話的時區(qū)
mysql> show variables like '%time_zone%'; +------------------+--------+| Variable_name | Value |+------------------+--------+| system_time_zone | CST || time_zone | SYSTEM |+------------------+--------+2 rows in set (0.00 sec)mysql> set time_zone='+0:00';Query OK, 0 rows affected (0.00 sec)mysql> select * from test;+------+---------------------+| id | hiredate |+------+---------------------+| 1 | 2015-12-07 16:00:00 |+------+---------------------+1 row in set (0.00 sec)mysql> select * from test1;+------+---------------------+| id | hiredate |+------+---------------------+| 1 | 2015-12-08 00:00:00 |+------+---------------------+1 row in set (0.01 sec)
新聞熱點
疑難解答
圖片精選