DATACMNS-1243 - Add converters from LocalDateTime to Instant and back.
This allows usage of Instant for AuditAware. Original pull request: #268.
This commit is contained in:
committed by
Oliver Gierke
parent
796ae8543d
commit
63577569bd
@@ -26,6 +26,7 @@ import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Period;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
@@ -67,6 +68,8 @@ public abstract class Jsr310Converters {
|
||||
converters.add(LocalTimeToDateConverter.INSTANCE);
|
||||
converters.add(DateToInstantConverter.INSTANCE);
|
||||
converters.add(InstantToDateConverter.INSTANCE);
|
||||
converters.add(LocalDateTimeToInstantConverter.INSTANCE);
|
||||
converters.add(InstantToLocalDateTimeConverter.INSTANCE);
|
||||
converters.add(ZoneIdToStringConverter.INSTANCE);
|
||||
converters.add(StringToZoneIdConverter.INSTANCE);
|
||||
converters.add(DurationToStringConverter.INSTANCE);
|
||||
@@ -167,6 +170,26 @@ public abstract class Jsr310Converters {
|
||||
}
|
||||
}
|
||||
|
||||
public static enum LocalDateTimeToInstantConverter implements Converter<LocalDateTime, Instant> {
|
||||
|
||||
INSTANCE;
|
||||
|
||||
@Override
|
||||
public Instant convert(LocalDateTime source) {
|
||||
return source.atZone(systemDefault()).toInstant();
|
||||
}
|
||||
}
|
||||
|
||||
public static enum InstantToLocalDateTimeConverter implements Converter<Instant, LocalDateTime> {
|
||||
|
||||
INSTANCE;
|
||||
|
||||
@Override
|
||||
public LocalDateTime convert(Instant source) {
|
||||
return LocalDateTime.ofInstant(source, systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
@WritingConverter
|
||||
public static enum ZoneIdToStringConverter implements Converter<ZoneId, String> {
|
||||
|
||||
|
||||
@@ -138,6 +138,17 @@ public class Jsr310ConvertersUnitTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test // DATACMNS-1243
|
||||
public void convertsLocalDateTimeToInstantAndBack() {
|
||||
|
||||
LocalDateTime dateTime = LocalDateTime.now();
|
||||
|
||||
Instant instant = CONVERSION_SERVICE.convert(dateTime, Instant.class);
|
||||
LocalDateTime convertedDateTime = CONVERSION_SERVICE.convert(dateTime, LocalDateTime.class);
|
||||
|
||||
assertThat(convertedDateTime, is(dateTime));
|
||||
}
|
||||
|
||||
private static String format(Date date, String format) {
|
||||
return new SimpleDateFormat(format).format(date);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user