且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检索存储在数据库中的日期的时区

更新时间:2023-01-30 19:41:50

如果您在没有时区的情况下存储 DATE ,则无法查询时区。



作为开发者,需要决定如何处理时区。请记住您有三个时区:
$ b $ ul

  • 数据库服务器时区
  • Web应用程序服务器时区。

  • 客户端浏览器时区



  • 如果洛杉矶的用户输入时间,在巴黎的用户应该看到什么?



    如果悉尼用户执行操作,多伦多用户应该看到什么操作时间戳?



    直到你能回答这些问题,即定义你的需求,解决方案/实现是不可能编码/验证的。 ,基本上有两种方式来处理时区:


    1. 将所有日期存储在固定时区中,例如UTC,并根据需要进行转换,几乎无处不在。

    2. 使用时区存储日期,并根据需要转换或显示时区。用户可能更喜欢转换,但这是您做出的设计决定。


    My J2EE application is deployed in cluster and servers can be in multiple timezones. For example one server is in EST and another server in CST.

    Consider a scenario where request goes to server in EST and store the date and time in database (without timezone). There is another request to retrieve the same date. But that request may go to another server in CST.

    Is there any way to determine which time zone date is stored in database?

    PS: I am using Oracle/Java/Hibernate.

    No. If you store the DATE without a time zone, there is no way to query the time zone.

    You, as the developer, needs to decide how time zones are handled. Remember you have 3 time zones:

    • Database server time zone.
    • Web Application server time zone.
    • Client Browser time zone.

    If a user in Los Angeles enters a time, what should a user in Paris see?

    If a user in Sydney performs an action, what action timestamp should a user in Toronto see?

    Until you can answer those questions, i.e. define your requirements, a solution/implementation is impossible to code/verify.

    As mentioned in a comment, there are basically two ways to handle time zones:

    1. Store all dates in a fixed time zone, e.g. UTC, and convert where needed, which is pretty much everywhere.
    2. Store dates with timezone, and either convert as needed or display with time zone. Users would likely prefer conversions, but that is a design decision for you to make.