Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save TimeZone with Date in mongodb

I have java.util.Date field in my document class.

E:g:

@Document(collection = "testdoc")
public class TestDoc {
    @Id
    String id;
    Date startDate;
}

Even if I set the Date with UTC and IST, it always save in my collection as below,

 "startDate" : ISODate("2015-08-21T18:30:00.000Z")

How can I save the time zone also in mongo collection? What does Z stand in this case?

like image 976
Harshana Avatar asked Dec 02 '22 12:12

Harshana


2 Answers

Do the conversion before storing and save as UTC always. Then reconvert it in the timezone you want before displaying.

If you desperately want to store the timezone with the offset you may have to deal with it as a separate string in db, but it cannot go with date field for MongoDB.

As currently MongoDB doesn't allow saving of timezone. Below is the open JIRA issue or the same.

https://jira.mongodb.org/browse/SERVER-6310

like image 60
mhasan Avatar answered Dec 15 '22 01:12

mhasan


The 'Z' signifies that the time is stored in UTC. Mongo internally converts all local representations of time in UTC before storing. However, one suggestion would be to store the time along with the timezone which is received from your application. You can later reconstruct the local time from the UTC time and the timezone in your application logic.

Please go through this link. They have given an example on how to model local time data using JavaScript.

https://docs.mongodb.com/v3.2/tutorial/model-time-data/

like image 33
Anirudh Srinivas Madhavan Avatar answered Dec 15 '22 02:12

Anirudh Srinivas Madhavan