How to store original date/time without timezone calculation to MongoDb
I managed to fix this using ZonedDateTime instead of LocalDateTime:
In the spring data mongo document definition
@Field("eventTime")
private ZonedDateTime eventTime;
Mongo doesnt have its own converter for ZonedDateTime so I created my own:
public class ZonedDateTimeReadConverter implements Converter<Date, ZonedDateTime> {
@Override
public ZonedDateTime convert(Date date) {
return date.toInstant().atZone(ZoneOffset.UTC);
}
}
and
public class ZonedDateTimeWriteConverter implements Converter<ZonedDateTime, Date> {
@Override
public Date convert(ZonedDateTime zonedDateTime) {
return Date.from(zonedDateTime.toInstant());
}
}
We also need to register it in MongoDbConfig class like:
@Configuration
public class MongoDbCommonConfiguration {
@Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
@Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
@Bean
@Primary
public CustomConversions customConversions() {
ZonedDateTimeReadConverter zonedDateTimeReadConverter = new ZonedDateTimeReadConverter();
ZonedDateTimeWriteConverter zonedDateTimeWriteConverter = new ZonedDateTimeWriteConverter();
return new CustomConversions(Arrays.asList(zonedDateTimeReadConverter, zonedDateTimeWriteConverter));
}
}
and when I get my events provider, I'm changing its LocalDateTime to ZonedDateTime at UTC zone like:
return new Event(providerEvent.getTime().atZone(ZoneId.of("UTC")), providerEvent.getName(),...);
and now when I got 18:00 from the provider for the event, 18:00 will be saved to the mongodb..
MongoDB - Storing date without timezone
Look at this answer: https://stackoverflow.com/a/6776273/6105830
You can use two types of long representation (milliseconds or format yyyyMMddHHmmss). These are the only ways to not store timezone and still be able to make range queries.
Unfortunately you lost some aggregation properties. But you can do something like keeping two representations and use them at opportune times.
UPDATE:
Do not store date as I said before. You will lost many and many features of MongoDB and also will be hard to perform major operators on date fields.
Newer versions of MongoDB has operators to deal with timezone, and it should be enough to work with ISOTime formats. My application was using my own suggestion to store date. Now I have to let my users select their TimeZone (company has grown and we need to expand to other countries). We are struggling to change all models to use timestamp instead of a normalized date format.
For further more explore the link: https://docs.mongodb.com/manual/reference/method/Date/
and you can also use MongoDB official community channel for questioning
Here is the link: https://developer.mongodb.com/community/forums/
Store date in MongoDB without considering the timezone
Whole dates should not be placed in a Date
object. Despite the name, Date
represents a date and a time. If the value you're working with represents a whole date, rather than a specific time on that date, then you should store the value in another format.
Options are:
- A string in
YYYY-MM-DD
orYYYYMMDD
format - An integer number of whole days since some reference point.
How to insert date in mongo DB without timezone
Your question is not consistent with your example. Your example shows storing the date without the time portion of the date, but your question is about storing the date without the timezone.
MongoDB doesn't store timezone as part of the date, all dates are stored in UTC. See Model Time Data for more details.
If you want to store the date without the time (as you show in your example), then "truncate" the date. You will still have a full Date object, with the time appearing as midnight UTC, but that's a fairly typical way of handling dates as you describe.
Since you're using Java, here are a few ways to truncate the date : Java Date cut off time information
How to save LocalDate to MongoDB without time (why is mongo saving date with time even if i save just the date)?
This is happening because MongoDB stores data in BSON format (see the BSON spec).
There is no datatype in BSON for Date
, there is only Timestamp
and UTC Datetime
both of which are stored as a 64-bit integer. UTC datetime is the number of milliseconds since epoch, leading to the time portion being all zeroes when it is rendered.
If you want to store just the date, you'll need to use a string type.
If the issue is how the data is displayed, you'll just need a different function to convert the timestamp returned from MongoDB to the display format you want to use.
String to Date conversion does not retain UTC date
If you see 2020-07-27T20:00:00-04:00
then it is because your client application displays the datetime in your local time zone. Which client do you use? There is no "mongo gui tool".
You have the native monogo
command shell, there is works as expected:
admin@so> db.bills.insertOne({
... billNumber: "B123",
... generatedOn: "2020-07-28T00:00:00Z"
... })
{
"acknowledged" : true,
"insertedId" : ObjectId("5f22585fb8ea3f41ce15fd78")
}
admin@so> db.bills.find({ billNumber: "B123" }).forEach(function (data) {
... data.generatedOn = ISODate(data.generatedOn);
... db.bills.save(data);
... });
admin@so> db.bills.find({}).pretty()
{
"_id" : ObjectId("5f22585fb8ea3f41ce15fd78"),
"billNumber" : "B123",
"generatedOn" : ISODate("2020-07-28T00:00:00Z")
}
If you like to output the date in specific format or time zone use $dateToString()
How can I turn UTC Timezone off for MongoDB
I don't think it's possible from the db level. What I did, was to write custom setter for date properties which will force mongoDB to assume the time is already in UTC, thus avoid a conversion like below:
private DateTime _createdUTC;
public DateTime CreatedUtc
{
get
{
return _createdUTC;
}
set
{
_createdUTC = new DateTime(value.Ticks, DateTimeKind.Utc);
}
}
Related Topics
Classcastexception Because of Classloaders
Where Does Gradle Save Dependencies' Jars
Java Cut String After 2 Decimal Digits
Making a Mocked Method Return an Argument That Was Passed to It
Passing Empty List as Parameter to JPA Query Throws Error
Spring Boot Controller Not Mapping
Spring Data Repository @Query - Update and Return Modified Entity
Source Folder Is Not on the Java Build Class Path, Creating Java Package
How to Write New Line Character to a File in Java
Use a Binary Search on an Int Array Sorted in Descending Order
Using an Empty Keystore Password Used to Be Possible
Spring Boot @Autowired Environment Throws Nullpointerexception
Java.Sql.Sqlexception: Field Doesn't Have a Default Value
Post and Get for the Same Url - Controller - Spring
Read Huge Excel File(500K Rows) in Java
How to Use Limit in Spring Within SQL Query