MySQL データベースの TIMESTAMP データ型

最近のプロジェクトで、アプリが新しいデータを追加するためにインターフェイスを呼び出したときに、挿入に失敗したことが判明し、ログを確認するとエラーが報告されました。

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 の公式ドキュメントを確認すると、タイムスタンプの種類の説明が確認できます。

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.

サポートされているタイムスタンプの範囲は 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 は、保存時にタイムスタンプ タイプ フィールドを現在のタイム ゾーンから 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 になります。タイムスタンプタイプの範囲内にありません。Guilty~



著者: ニックネームはありません
リンク: https://www.jianshu.com/p/efcd369981e0
出典: Jianshu
Jianshu の著作権は著者に帰属します。いかなる形式の転載についても、著者に連絡して許可を得て、出典を明示してください。 。

おすすめ

転載: blog.csdn.net/danny_799745061/article/details/89383381