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?

Lars Bohl
  • 1,001
  • 16
  • 20
  • 1
    It depends on JVM settings, for example on system property "user.timezone", too, see also [getting default zone](http://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html#systemDefault--) – Meno Hochschild Jun 09 '16 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. – Lars Bohl Jun 09 '16 at 12:02
  • 2
    Possible duplicate of [Timezones in SQL DATE vs java.sql.Date](http://stackoverflow.com/questions/9202857/timezones-in-sql-date-vs-java-sql-date) – Jordi Castilla Jun 09 '16 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. – Lars Bohl Jun 09 '16 at 12:19

2 Answers2

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
JodaStephen
  • 60,927
  • 15
  • 95
  • 117
  • 1
    Does that mean that `date.toLocalDate()` will return different LocalDate objects, depending on the system timezone of the current JVM? – Lars Bohl Jun 09 '16 at 12:10
  • 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... – marcus Dec 07 '16 at 14:16
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