ZonedDateTimeConverter extends AbstractJava8DateTimeConverter { @Override public Object convert(Class destClass, Object srcObject) { Class<?> srcObjectClass = srcObject.getClass(); if (Date.class.isAssignableFrom(srcObjectClass)) { Instant instant = ((Date)srcObject).toInstant(); return ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()); } else if (Instant.class.isAssignableFrom(srcObjectClass)) { return ZonedDateTime.ofInstant((Instant)srcObject, ZoneId.systemDefault()); } else if (Long.class.isAssignableFrom(srcObjectClass)) { Instant instant = Instant.ofEpochMilli((Long)srcObject); return ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()); } else { return super.convert(destClass, srcObject); } } ZonedDateTimeConverter(DateTimeFormatter formatter); @Override Object convert(Class destClass, Object srcObject);  }
@Test public void canConvertFromToZonedDateTime() { ZonedDateTime sourceObject = ZonedDateTime.of(LocalDateTime.of(2017, 11, 2, 10, 0), ZoneId.systemDefault()); ZonedDateTime expected = ZonedDateTime.of(LocalDateTime.of(2017, 11, 2, 10, 0), ZoneId.systemDefault()); Object result = converter.convert(ZonedDateTime.class, sourceObject); assertTrue(result instanceof ZonedDateTime); assertEquals(expected, result); }
@Test public void canConvertFromStringToZonedDateTime() { String sourceObject = "2017-11-02T10:20:30+01:00[Europe/Madrid]"; ZonedDateTime expected = ZonedDateTime.of(LocalDateTime.of(2017, 11, 2, 10, 20, 30), ZoneId.of("Europe/Madrid")); Object result = converter.convert(ZonedDateTime.class, sourceObject); assertTrue(result instanceof ZonedDateTime); assertEquals(expected, result); }
@Test public void canConvertFromInstantToZonedDateTime() { Instant sourceObject = Instant.parse("2017-11-02T10:20:30.00Z"); ZonedDateTime expected = ZonedDateTime.ofInstant(Instant.parse("2017-11-02T10:20:30.00Z"), ZoneId.systemDefault()); Object result = converter.convert(ZonedDateTime.class, sourceObject); assertTrue(result instanceof ZonedDateTime); assertEquals(expected, result); }
@Test public void canConvertFromLongToZonedDateTime() { Long sourceObject = Instant.parse("2017-11-02T10:20:30.00Z").toEpochMilli(); ZonedDateTime expected = ZonedDateTime.ofInstant(Instant.parse("2017-11-02T10:20:30.00Z"), ZoneId.systemDefault()); Object result = converter.convert(ZonedDateTime.class, sourceObject); assertTrue(result instanceof ZonedDateTime); assertEquals(expected, result); }
@Test public void canConvertFromDateToZonedDateTime() { Date sourceObject = new Date(Instant.parse("2017-11-02T10:20:30.00Z").toEpochMilli()); ZonedDateTime expected = ZonedDateTime.ofInstant(Instant.parse("2017-11-02T10:20:30.00Z"), ZoneId.systemDefault()); Object result = converter.convert(ZonedDateTime.class, sourceObject); assertTrue(result instanceof ZonedDateTime); assertEquals(expected, result); }