Reputation: 4513
I have a really strange problem about showing dates. And particulary in windows. I dont know why, when i get a Date from a query (Hibernate) it gives me one day less. when the data gets to the server the date is fine but when it gets to the client it gives one day less. For example: in the server the date is Fri Sep 24 00:00:00 1982 but when it gets to the client is Thu Sep 23 23:00:00 1982. As you can see its one difference day.
Ah and i almost forget to mention it happens on windows (Seven) as its TimeZone its UTC instead of GMT. Me and my colegues use Linux and there is no problem with it.
Is there any workaround about this?
Thanks in advance!
Upvotes: 1
Views: 1244
Reputation: 338181
As Jon Skeet correctly points, likely you have a time zone problem. Likely your middleware tools are dynamically applying a default time zone, a well-intentioned but very confusing anti-feature.
The modern solution is to use the java.time classes added to Java 8 and later.
As of JDBC 4.2, we can exchange java.time objects with the database. Hibernate and JPA have been updated to handle java.time as well.
Retrieval from a column of type akin to TIMESTAMP WITH TIME ZONE
.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Writing.
myPreparedStatement.setObject( … , odt ) ;
By using these objects, you will avoid your middleware tool from applying a time zone. With JDBC 4.2 retrieving java.time objects, you will see the value as it was truly stored.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Upvotes: 2
Reputation: 1499770
It's not giving you a value a day earlier. It's giving you a value an hour earlier (midnight on September 24th vs 11pm on September 23rd).
That's almost certainly a time zone issue, which is almost certainly just a reflection of how you're formatting your dates. If you use SimpleDateFormatter
, just set the TimeZone
appropriately (your actual requirements will determine which zone that is) and you should get the same results.
As an aside, in general I'd recommend using Joda Time as far as possible when it comes to date/time work in Java - it's a much cleaner API than Date
and Calendar
.
Upvotes: 4