I was writing some testcode for java-8 conversion between java.util.Date and java.time.LocalDateTime, and discovered an anomaly seems to occur in the hour after the transition from normaltime-to-summertime, when the year is 2038 or higher.
I just wanted to know if this is a bug in jdk8, or if I am doing something wrong?
Note: I am on Windows-7, 64-bit jdk, so should not be affected by the 2038-unix bug, which would have a much worse effect.
Here my demo-code:
package conversiontest;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
public class ConversionTest {
public static void main(String[] args) {
new ConversionTest().testDateConversion();
}
// Method under test:
public java.util.Date toJavaUtilDate(LocalDateTime localDateTime) {
return java.util.Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
// Test-code:
public void testDateConversion() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
LocalDate localDate = LocalDate.of(2016, 1, 1);
LocalTime localTime = LocalTime.of(3, 22, 22); // 03:22:22
while (!localDate.toString().startsWith("2045-")) {
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
java.util.Date date = toJavaUtilDate(localDateTime);
String sLocalDateTime = localDateTime.toString().replace("T", " ");
String sJavaUtilDate = sdf.format(date);
if (!sLocalDateTime.equals(sJavaUtilDate)) {
System.out.println(String.format("FAILURE: '%s' != '%s'", sLocalDateTime, sJavaUtilDate));
}
localDate = localDate.plusDays(1);
}
}
}
Output:
FAILURE: '2038-03-28 03:22:22' != '2038-03-28 02:22:22'
FAILURE: '2039-03-27 03:22:22' != '2039-03-27 02:22:22'
FAILURE: '2040-03-25 03:22:22' != '2040-03-25 02:22:22'
FAILURE: '2041-03-31 03:22:22' != '2041-03-31 02:22:22'
FAILURE: '2042-03-30 03:22:22' != '2042-03-30 02:22:22'
FAILURE: '2043-03-29 03:22:22' != '2043-03-29 02:22:22'
FAILURE: '2044-03-27 03:22:22' != '2044-03-27 02:22:22'
As you can see from the output, LocalDateTime(2038-03-28 03:22:22) gets converted to java.util.Date(2038-03-28 02:22:22), etc. But not when the year is lower than 2038.
Anyone has some input to this?
EDIT:
My ZoneId.systemDefault() gives: "Europe/Berlin"
C:\>java -version
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b15, mixed mode)
C:\>javac -version
javac 1.8.0_91