还是之前工作中遇到的一个小问题。我在做一个收据采集的程序,需要记录起始时间和结束时间,在数据库中是用timestamp字段来保存的,有些情况下不存在起始时间,此时就需要设置一个默认的起始时间,当初想着是使用timestamp类型的『最小值』。
然而,从1970-01-01 00:00:00
到1970-01-01 00:00:01
,保存到数据库的时候总是报错,后面使用1970-01-01 08:00:01
终于就正常了。后来又参考了
http://blog.itpub.net/25281640/viewspace-710118/
这篇文章的观点论证了。
从此开始我就认为timestamp
的范围,就像文章的观点,真正的范围是从1970-01-01 08:00:01 到 2038-01-19 11:14:07
。这个08:00:01
当时并没有引起我的注意,最近不知怎么突然想起来,感觉不对。
从MySQL的官方文档就可以得到结论,http://dev.mysql.com/doc/refman/5.0/en/datetime.html
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of ‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC.
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.) By default, the current time zone for each connection is the server’s time. The time zone can be set on a per-connection basis. As long as the time zone setting remains constant, you get back the same value you store. If you store a TIMESTAMP value, and then change the time zone and retrieve the value, the retrieved value is different from the value you stored. This occurs because the same time zone was not used for conversion in both directions. The current time zone is available as the value of the time_zone system variable. For more information, see Section 10.6, “MySQL Server Time Zone Support”.
timestamp
类型的起始时间是1970-01-01 00:00:01 UTC
,和时区是关系的。如果我没有理解错的话,MySQL将timestamp类型的值保存的时候,会从当前时区转成UTC时间,正好解释了前面1970-01-01 00:00:00
或1970-01-01 00:00:01
两个值保存时出错的问题了。从当前时区转成UTC时间需要减去『8小时』,结果就不在timestamp
类型的范围内了。