3

I'm surprised that java.sql.Date has a method toLocalDate().

java.util.Date or java.time.Instant don't have comparable methods. It seems that in java.time, a ZoneId must always be provided to obtain "LocalFoo" or "OffsetBar".

From the javadoc of java.sql.Date#toLocalDate():

Converts this Date object to a LocalDate. The conversion creates a LocalDate that represents the same date value as this Date in local time zone

Which timezone is "local time zone"? Does it depend on database or JVM settings?

4
  • 1
    It depends on JVM settings, for example on system property "user.timezone", too, see also getting default zone Commented Jun 9, 2016 at 12:00
  • Are you sure? It seems a bit odd with the other parts of java.time, that this default can not be overridden or made explicit. Commented Jun 9, 2016 at 12:02
  • 2
    Possible duplicate of Timezones in SQL DATE vs java.sql.Date Commented Jun 9, 2016 at 12:05
  • That question looks very related, and I guess it means that it depends on system settings indeed. However toLocalDate is not mentioned there, and an explicit answer to that specific question would be nice. Commented Jun 9, 2016 at 12:19

2 Answers 2

5

Conceptually, a java.sql.Date is the same as a LocalDate, ie. a date without time or time-zone. In practice, because java.sql.Date is implemented based on a long milliseconds, it has an implicit use of the system time-zone. So, the toLocalDate() method exists because the Java SQL spec leads want you to think of java.sql.Date as being without a time-zone.

Sign up to request clarification or add additional context in comments.

2 Comments

Does that mean that date.toLocalDate() will return different LocalDate objects, depending on the system timezone of the current JVM?
So that's why the method has @SuppressWarnings("deprecation")? It's funny because java.util.Date deprecates most methods and java.sql.Date undeprecates some of them...
2

given a java.sql.Date-Object wrapping a fix millisecondsvalue, you will indeed get different LocalDate-Values depending on the Default-Timezone on your System.

I tried the following Code-Snippet:

TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
java.sql.Date sqlDate = new java.sql.Date(1465485798671l);
System.out.println(sqlDate.toLocalDate());
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo"));
System.out.println(sqlDate.toLocalDate());

which yields: 2016-06-09 2016-06-10

3 Comments

Hang on, there's no toLocalDate in that code. What happens when we add it?
Hi Lars, sorry I forgot indeed to add .toLocalDate() - i've edited the code.
Excellent answer. Accepted!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.