MySQL中timestamp類型支持范圍

最近項目中App端調用接口新增數據時,發現插入失敗,查看日志發現報錯

Cause: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '1970-01-01 08:00:00' for column 'lastModifyTime' at row 1

原來是lastModifyTime字段插入的值不支持,但這個字段一般是不需要前臺傳入的,可以在MySQL中設置該字段默認為當前時間,并根據當前時間戳更新。但是仔細看報錯信息,1970-01-01 08:00:00這個時間明明看起來在格式上沒有任何問題啊,為什么會插入不了呢?排除了其他可能的原因后,懷疑可能是這個值的問題,查閱MySQL的官方文檔,可以看到其中對于timestamp類型的說明

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.

原來timestamp支持的范圍是1970-01-01 00:00:01到2038-01-19 03:14:07,那為什么1970-01-01 08:00:00看起來是在這個范圍內卻不支持呢,繼續往下看

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”.

MySQL文檔中支持的時間范圍后面都添加了UTC,說明這個時間是和時區相關的,MySQL在存儲的時候會將timestamp類型的字段從當前時區轉成UTC時區。我們可以查看一下當前時區

show variables like "%time_zone%";
+------------------+--------+
| Variable_name    | Value  |
+------------------+--------+
| system_time_zone | CST    |
| time_zone        | SYSTEM |
+------------------+--------+

從當前時區轉成UTC時區需要減去8小時,所以最后1970-01-01 08:00:00這個時間存儲到MySQL其實變成了1970-01-01 00:00:00,不在timestamp類型的范圍內了~

參考:MySQL的timestamp字段可以使用的范圍是多少

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容