I am running into few issues around handling dates in my project. This is what I have.
- In My Entities, I am using ZonedDateTime.
private ZonedDateTime assignedOn;
Have Configured converters in Spring to handle this
public static class ZonedDateTimeToDateConverter implements Converter { public static final ZonedDateTimeToDateConverter INSTANCE = new ZonedDateTimeToDateConverter(); private ZonedDateTimeToDateConverter() {}
@Override public Date convert(ZonedDateTime source) { return source == null ? null : Date.from(source.toInstant()); } } public static class DateToZonedDateTimeConverter implements Converter<Date, ZonedDateTime> { public static final DateToZonedDateTimeConverter INSTANCE = new DateToZonedDateTimeConverter(); private DateToZonedDateTimeConverter() {} @Override public ZonedDateTime convert(Date source) { return source == null ? null : ZonedDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault()); } }
I see that data is stored in Mongodb as ISO date. This what i see in Mongodb.
"completed_on" : ISODate("2017-04-12T20:02:40.000+0000"),
My Question is related to querying these date fields using Spring. If I want to find all the records (equals operator) matching only the date part and not the time part, what should be the approach? I saw example in this thread
Spring data mongodb search for ISO date
Which suggest something like this.
query.addCriteria(Criteria.where("created").ne(null).andOperator(
Criteria.where("created").gte(DateUtils.getDate("2016-04-14 00:00:00", DateUtils.DB_FORMAT_DATETIME)),
Criteria.where("created").lte(DateUtils.getDate("2016-04-14 23:59:59", DateUtils.DB_FORMAT_DATETIME))
));
Just wanted to see if this is the only approach or there's another elegant way to do this?