Last active
September 15, 2023 14:56
-
-
Save wpik/87ddeaf73b84b02a97c9827cf2a5bc8c to your computer and use it in GitHub Desktop.
OffsetDateTime converters in Mongo in Spring
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 org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.core.convert.converter.Converter; | |
import org.springframework.data.mongodb.core.convert.MongoCustomConversions; | |
import java.time.OffsetDateTime; | |
import java.time.ZoneOffset; | |
import java.util.List; | |
@Configuration | |
public MongoConvertersConfig { | |
@Bean | |
public MongoCustomConversions mongoCustomConversions() { | |
return new MongoCustomConversions(List.of( | |
new OffsetDateTimeReadConverter(), | |
new OffsetDateTimeWriteConverter() | |
)); | |
} | |
static class OffsetDateTimeWriteConverter implements Converter<OffsetDateTime, String> { | |
@Override | |
public String convert(OffsetDateTime source) { | |
return source.toInstant().atZone(ZoneOffset.UTC).toString(); | |
} | |
} | |
static class OffsetDateTimeReadConverter implements Converter<String, OffsetDateTime> { | |
@Override | |
public OffsetDateTime convert(String source) { | |
return OffsetDateTime.parse(source); | |
} | |
} | |
} |
Just an update here, there is an issue during the read process, the write converter is setting the ZoneId which is creating a ZonedDateTime. ZonedDateTime format is different than the OffsetDateTime.
Example:
- ZonedDateTime:
2022-09-30T03:47:52.688159-03:00[America/Sao_Paulo]
- OffsetDateTime:
2022-09-30T03:47:52.688159-03:00
To fix this issue here's what I did (Kotlin):
class OffsetDateTimeWriteConverter : Converter<OffsetDateTime, String> {
override fun convert(source: OffsetDateTime): String {
return source.toInstant().atZone(ZoneOffset.UTC).toOffsetDateTime().toString()
}
}
Also, if you are using the @EnableMongoAuditing
, here's something else you need to add:
@EnableMongoRepositories
@EnableMongoAuditing(dateTimeProviderRef = "auditingDateTimeProvider") // <<<<< -- Make sure to reference the provider here.
class MongoConfig {
@Bean("auditingDateTimeProvider")
fun auditingDateTimeProvider(): DateTimeProvider {
return DateTimeProvider { Optional.of(OffsetDateTime.now()) }
}
....
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
works like a charm! Thank you! (PS: you are missing the "class" after public on line 11;D)