InstantConverter implements Converter { @Override public Object convert(Class destClass, Object srcObject) { Class<?> srcObjectClass = srcObject.getClass(); if (Date.class.isAssignableFrom(srcObjectClass)) { Instant instant = ((Date) srcObject).toInstant(); return instant; } else if (Instant.class.isAssignableFrom(srcObjectClass)) { return Instant.from((Instant) srcObject); } else if (TemporalAccessor.class.isAssignableFrom(srcObjectClass)) { return Instant.from((TemporalAccessor) srcObject); } else if (String.class.isAssignableFrom(srcObjectClass)) { return Instant.parse((String) srcObject); } else { throw new ConversionException(String.format("Unsupported source object type: %s", srcObjectClass), null); } }  @Override Object convert(Class destClass, Object srcObject);  }
@Test public void canConvertFromInstantToInstant() { Instant sourceObject = ZonedDateTime.of(LocalDateTime.of(2017, 11, 2, 10, 0), ZoneOffset.UTC).toInstant(); Instant expected = ZonedDateTime.of(LocalDateTime.of(2017, 11, 2, 10, 0), ZoneOffset.UTC).toInstant(); Object result = converter.convert(Instant.class, sourceObject); assertTrue(result instanceof Instant); assertEquals(expected, result); }
@Test public void canConvertFromStringToInstant() { String sourceObject = "2017-11-02T10:20:30.00Z"; Instant expected = ZonedDateTime.of(LocalDateTime.of(2017, 11, 2, 10, 20, 30), ZoneOffset.UTC).toInstant(); Object result = converter.convert(Instant.class, sourceObject); assertTrue(result instanceof Instant); assertEquals(expected, result); }
@Test public void canConvertFromZonedDateTimeToInstant() { ZonedDateTime sourceObject = ZonedDateTime.of(LocalDateTime.of(2017, 11, 2, 10, 20, 30), ZoneOffset.UTC); Instant expected = ZonedDateTime.of(LocalDateTime.of(2017, 11, 2, 10, 20, 30), ZoneOffset.UTC).toInstant(); Object result = converter.convert(Instant.class, sourceObject); assertTrue(result instanceof Instant); assertEquals(expected, result); }
@Test public void canConvertFromDateToInstant() { Date sourceObject = new Date(Instant.parse("2017-11-02T10:20:30.00Z").toEpochMilli()); Instant expected = ZonedDateTime.of(LocalDateTime.of(2017, 11, 2, 10, 20, 30), ZoneOffset.UTC).toInstant(); Object result = converter.convert(Instant.class, sourceObject); assertTrue(result instanceof Instant); assertEquals(expected, result); }