登录
首页 >  数据库 >  MySQL

MySQL timestamp字段可以用的范围是多少

来源:SegmentFault

时间:2023-02-18 19:54:21 313浏览 收藏

哈喽!今天心血来潮给大家带来了《MySQL timestamp字段可以用的范围是多少》,想必大家应该对数据库都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到MySQL,若是你正在学习数据库,千万别错过这篇文章~希望能帮助到你!

还是之前工作中遇到的一个小问题。我在做一个收据采集的程序,需要记录起始时间和结束时间,在数据库中是用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
类型的范围内了。

本篇关于《MySQL timestamp字段可以用的范围是多少》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于数据库的相关知识,请关注golang学习网公众号!

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>