Last active
June 2, 2021 13:55
-
-
Save marttp/7af96c55083b60b2c1e5c7d8f7ed4f45 to your computer and use it in GitHub Desktop.
[Spring WebFlux]: ReadingConverter & WritingConverter for ZonedDateTime inside MongoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.time.ZoneId; | |
import java.time.ZonedDateTime; | |
import java.time.temporal.ChronoUnit; | |
import java.util.ArrayList; | |
import java.util.Date; | |
import java.util.List; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.core.convert.converter.Converter; | |
import org.springframework.data.convert.ReadingConverter; | |
import org.springframework.data.convert.WritingConverter; | |
import org.springframework.data.mongodb.core.convert.MongoCustomConversions; | |
@Configuration | |
public class MongoConfig { | |
@Bean | |
public MongoCustomConversions mongoCustomConversions() { | |
List<Converter<?,?>> converters = new ArrayList<>(); | |
converters.add(ZonedDateTimeToDate.INSTANCE); | |
converters.add(DateToZonedDateTime.INSTANCE); | |
return new MongoCustomConversions(converters); | |
} | |
@ReadingConverter | |
enum DateToZonedDateTime implements Converter<Date, ZonedDateTime> { | |
INSTANCE; | |
@Override | |
public ZonedDateTime convert(Date date) { | |
return date.toInstant() | |
.atZone(ZoneId.systemDefault()) | |
.truncatedTo(ChronoUnit.MILLIS); | |
} | |
} | |
@WritingConverter | |
enum ZonedDateTimeToDate implements Converter<ZonedDateTime, Date> { | |
INSTANCE; | |
@Override | |
public Date convert(ZonedDateTime zonedDateTime) { | |
return Date.from(zonedDateTime.toInstant()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment