Mysql Timestamp

805 查看

格式

YYYY-MM-DD HH:MM:SS, 固定19个字符长度

范围

'1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC
UTC是协调世界时,又称世界标准

时区

插入一个timestamp类型的值时, mysql会将你当前客户端连接的时区转换成UTC来储存.默认为你的mysql server所在的时区

create table test_timestamp(
t1 timestamp
)

设置时区:
set time_zone = '+00:00';
插入一条数据:
insert into test_timestamp values('2014-06-20 00:00:01');
查询:
select t1 from test_timestamp;
结果:
2014-06-20 00:00:01
如果将时区修改为
set time_zone = '+03:00'
则查询出来的结果为
2014-06-20 00:03:01
p.s: 时区特性只有timestamp类型才有

自动初始化和自动更新特性

首先创建一张有两个timestamp列的表

create table ts(
id int auto_increment primary key,
title varchar(255) not null,
changed_on timestamp,
created_on timestamp
)

然后插入一条新记录
inset into ts(title) values('test mysql timestamp');
之后select出来的结果

id title changed_on created_on
1 mysql test timestamp update 2014-06-22 12:15:21 0000-00-00 00:00:00

最后更新这条记录
update ts set title = 'test mysql timestamp update' where id = 1;
select出来的结果

id title changed_on created_on
1 mysql test timestamp update 2014-06-22 12:20:34 0000-00-00 00:00:00

总结

1.默认情况下,如果插入时没有指定第一个timestamp列的值,mysql则设置这个列的值为当前时间。在更新记录时,mysql也会更新这个列的值为当前时间。
2.timestamp列默认为not null.
3.只能够有一个timestamp列出现 CURRENT_TIMESTAMP 声明,无论是在DEFAULT 抑或 ON UPDATE 语句中