It is unfortunate, but all the answers so far, as a rule, are incorrect. The answer is quite simple, but it requires five points:
- DATE = java.sql.Date, which is a wrapper around java.util.Date, which is the number of milliseconds since the Age in the UTC time zone. So it has year / month / date / hours / minutes / seconds in a fixed time zone of GMT + 0 (UTC). Note, however, that java.sql.Date sets the time components to zero!
- TIMESTAMP = java.sql.TimeStamp, which is a wrapper for the Date component that adds fractional seconds to support a standard like SQL DATE. This class / type is not relevant or necessary for this question, but, in short, it is a date plus time.
- The database stores DATE objects as defined (using UTC as an offset from Java), but can transfer time, if configured in the database, to a different time zone. By default, most databases default to the time zone of the local server, which is a very bad idea. Ladies and gentlemen ... ALWAYS store DATE objects in UTC. Read on ...
- The time in the JVM and time zone must be correct. Since the Date object uses UTC, is offset calculation done for your time server? Think with a strong recommendation to set the server time to GMT + 0 (UTC).
- Finally, when we want to display DATE from the database (using JSF or something else), it must be set to GMT + 0 time zone and, if it is done on the server side, also ... your dates and time will ALWAYS be be consistent, referenced, and all good things. It remains only to display the time and IT, where a user agent (for example, for a web application) can be used to translate GMT + 0 time into the "local" time zone of users.
Summary: use UTC (GMT + 0) on the server, in the database, in your Java objects.
DATE and TIMESTAMP differ from the database in that TIMESTAMP contains an additional fraction of a second. Both use GMT + 0 (implied). JodaTime is the preferred calendar structure to solve all this, but will not fix inconsistent JVM issues for setting database time zones.
If application projects from the JVM to the database do not use GMT, due to the saving of daylight, adjusting the clock and all other regional games that play in the global local clock ... transaction times and everything else will be skewed, non-relational, inconsistent, etc. d.
Another good answer about data types: java.util.Date vs java.sql.Date
Also note that on Java 8 there are updates with improved date and time processing (finally), but this does not mean that the JVM server clock operates in one time zone and the database in another. At this moment, a translation always takes place. In every major (smart) client I work with, the time zones of the database and JVM servers are set to UTC for this very reason, even if their operations mainly occur in some other time zone.
Darrell teague
source share