一、相同点
IMESTAMP和DATETIME的相同点:
两者都可用来表示 YYYY-MM-DD HH:MM:SS 类型的日期。
二、不同点
1、两者的存储方式不一样
对于TIMESTAMP:
它把客户端插入的时间从当前时区转化为UTC(世界标准时间)进行存储。
查询时,将其又转化为客户端当前时区进行返回。
对于DATETIME:
不做任何改变,基本上是原样输入和输出。
2、两者所能存储的时间范围不一样
imestamp所能存储的时间范围为:'1970-01-01 00:00:01.000000' 到 '2038-01-19 03:14:07.999999'。
datetime所能存储的时间范围为:'1000-01-01 00:00:00.000000' 到 '9999-12-31 23:59:59.999999'。
3、总结:
TIMESTAMP和DATETIME除了存储范围和存储方式不一样,没有太大区别。当然,对于跨时区的业务,TIMESTAMP更为合适
三、试验
1、环境准备
create table test(id int,hiredate timestamp);
insert into test values(1,'20151208000000');
create table test1(id int,hiredate datetime);
insert into test1 values(1,'20151208000000');
mysql> select * from test;
+------+---------------------+
| id | hiredate |
+------+---------------------+
| 1 | 2015-12-08 00:00:00 |
+------+---------------------+
mysql> select * from test1;
+------+---------------------+
| id | hiredate |
+------+---------------------+
| 1 | 2015-12-08 00:00:00 |
+------+---------------------+
2、修改当前会话的时区
mysql> show variables like '%time_zone%';
+------------------+--------+
| Variable_name | Value |
+------------------+--------+
| system_time_zone | CST |
| time_zone | SYSTEM |
+------------------+--------+
mysql> set time_zone='+0:00';
mysql> select * from test;
+------+---------------------+
| id | hiredate |
+------+---------------------+
| 1 | 2015-12-07 16:00:00 |
+------+---------------------+
mysql> select * from test1;
+------+---------------------+
| id | hiredate |
+------+---------------------+
| 1 | 2015-12-08 00:00:00 |
+------+---------------------+
上述“CST”指的是MySQL所在主机的系统时间,是中国标准时间的缩写,China Standard Time UT+8:00
通过结果可以看出,test中返回的时间提前了8个小时,而test1中时间则不变。这充分验证了两者的区别。