简体   繁体   中英

Insert/Retrieve Date as per local time zone in MongoDB using Java

I am inserting the current date in a mongodb collection using java.

I am using the following code to do so:

BasicDBObject doc = new BasicDBObject("date",new Date()); coll.insert(doc);

It is saving the date in GMT not in my local timezone. But when I am inserting through shell using command: db.test.insert({date:Date()}); It is taking my local timezone.

Is there any way to insert Date as per local time zone format using java or any way to convert date to local timezone while retrieving.

Thanks & Regards

The java Date object is intentionally timezone-agnostic and supposed to represent GMT times (it internally stores its value as milliseconds since January 1, 1970, 00:00:00 GMT). I would really recommend you to work with this and internally handle all dates in GMT, because it saves you plenty of trouble with daylight saving time or when your application will be deployed in a distributed manner in multiple timezones.

To convert a Date object to or from strings representing it in the timezone of the user, use a SimpleDateFormat on which you called the setTimeZone method with the users TimeZone (the static method TimeZone.getDefault() gives you the time zone of the local system).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM