Timestamps and time zone conversions in Java and MySQL

后端 未结 2 484
后悔当初
后悔当初 2021-02-04 17:06

I\'m developing a Java application with a MySQL database on a server located in a different time zone from mine, and I am trying to decide between using DATETIME or TIMESTAMP on

2条回答
  •  时光说笑
    2021-02-04 17:46

    Your question is spot on a problem which i think is huge these days. Both DB (via SQL) and server side itself (via programming languages such as Java) offer a compendium of ways of dealing with date and time. I would qualify the status-quo as highly non-standardized and a bit chaotic (personal opinion :)

    My answer is partial but i'll explain why.

    You're correct, Java's Date (and Calendar) store time as milliseconds since the Unix Epoch (which is great). It happens not only in Java but in other programming languages as well. In my opinion the perfect time-keeping architecture emerges naturally from this: the Unix Epoch is January 1st, 1970, midnight, UTC. Therefore if you choose to store time as milliseconds since the Unix Epoch you have a lot of benefits:

    • architecture clarity: server side works with UTC, client side shows the time through its local timezone
    • database simplicity: you store a number (milliseconds) rather than complex data structures like DateTimes
    • programming efficiency: in most programming languages you have date/time objects capable of taking milliseconds since Epoch when constructed (which as you said, allows for automatic conversion to client-side timezone)

    I find code and architecture is much simpler and more flexible when using this approach. I stopped trying to understand things like DateTime (or Timestamp) and only deal with them when i have to fix legacy code.

提交回复
热议问题