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
8d732bca19
commit
0e9f150fa8
@@ -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;
|
||||
@@ -70,6 +71,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);
|
||||
@@ -178,6 +181,28 @@ public abstract class Jsr310Converters {
|
||||
}
|
||||
}
|
||||
|
||||
public static enum LocalDateTimeToInstantConverter implements Converter<LocalDateTime, Instant> {
|
||||
|
||||
INSTANCE;
|
||||
|
||||
@Nonnull
|
||||
@Override
|
||||
public Instant convert(LocalDateTime source) {
|
||||
return source.atZone(systemDefault()).toInstant();
|
||||
}
|
||||
}
|
||||
|
||||
public static enum InstantToLocalDateTimeConverter implements Converter<Instant, LocalDateTime> {
|
||||
|
||||
INSTANCE;
|
||||
|
||||
@Nonnull
|
||||
@Override
|
||||
public LocalDateTime convert(Instant source) {
|
||||
return LocalDateTime.ofInstant(source, systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
@WritingConverter
|
||||
public static enum ZoneIdToStringConverter implements Converter<ZoneId, String> {
|
||||
|
||||
|
||||
@@ -145,6 +145,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).isEqualTo(dateTime);
|
||||
}
|
||||
|
||||
private static Predicate<Date> formatted(Temporal expected, String format) {
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
|
||||
|
||||
Reference in New Issue
Block a user