MySQL DATETIME 與 TIMESTAMP 的差別

 

DATETIME 與 TIMESTAMP 的差別

參考官方的說明

The DATETIME type is used when you need values that contain both date and time information. MySQL retrieves and displays DATETIME values in ‘YYYY-MM-DD HH:MM:SS’ format. The supported range is ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’.

The TIMESTAMP data type has a range of ‘1970-01-01 00:00:01’ UTC to ‘2038-01-09 03:14:07’ UTC. It has varying properties, depending on the MySQL version and the SQL mode the server is running in.

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

簡單來說,兩個差別:
  • 支持的日期範圍不同:
    • DATETIME:1000-01-01 00:00:00 到 9999-12-31 23:59:59
    • TIMESTAMP:1970-01-01 00:00:01 UTC 到 2038-01-09 03:14:07 UTC
  • 儲存時對時區的處理:
    • DATETIME
      • 直接儲存不做任何轉換,你傳 2020-01-01 09:00 給 MySQL,MySQL 就當作是 2020-01-01 09:00 儲存。
      • 就算變更了 MySQL 時區,讀取出來也一樣是 2020-01-01 09:00。
    • TIMESTAMP
      • 儲存時會更根據 MySQL 時區先轉換成 UTC 時間,若 MySQL 時區是+8,你傳 2020-01-01 09:00 給 MySQL,MySQL 會轉成 2020-01-01 01:00 +00:00 儲存。
      • 讀取時會根據 MySQL 時區,將時間還原,以上例來說:
        • MySQL 時區還是+8,2020-01-01 01:00 +0000 會轉成 2020-01-01 09:00
        • 若讀取時 MySQL 時區改成+10,2020-01-01 01:00 +0000 會轉成 2020-01-01 11:00

要使用 DATETIME 還是 timestamp

如果你要儲存的日期範圍不在 1970-01-01 00:00:01 UTC 到 2038-01-09 03:14:07 UTC 之間,那就只有 DATETIME 可以選擇。但基本上西元2038年也不是太遠的未來了,所以現在應該都是優先使用 DATETIME。

PS:以上時間轉換只考慮到 MySQL 本身而已。若是你的程式跟 MySQL 串接,比如說 JDBC,JDBC 是會針對 MySQL 時區在儲存/讀取時作轉換的,請拆成兩個階段來思考比較好抓時區的問題。

0 則回應: