mongodb ISODate problems

回眸只為那壹抹淺笑 提交于 2019-12-04 12:23:49

The hour did not change. You must be in China, given the "CST" in your example and the 8 hour difference. If you interpret "CST" as "China Standard Time" (rather than Central Standard Time in the US), then you have a time zone that is 8 hours ahead of UTC/GMT. So when ti is 1 AM UTC/GMT, at the vary same moment the clock on the wall in Taipei will read "9 AM".

Minor point: Those three-letter codes for time zones are obsolete and should be avoided. They are neither standardized nor unique. Use proper time zone names.

Major point: The problem lies in how you extract a value from MongoDB that represents a date-time.

I don't know MongoDB, and their doc is confusing, so I can't help you much further. If you can retrieve an ISO 8601 string as seen in your first example, that is much preferable to the format of your second example.

If you want to work with the date-time value in Java, you can feed an ISO 8601 string directly to a DateTime constructor in Joda-Time 2.3.

DateTime dateTime = new DateTime( "2013-10-21T01:34:04.808Z" );

Update

This doc says that the Java driver for MongoDB will give you a java.util.Date object. That explains your problem. The java.util.Date & Calendar classes bundled with Java are notoriously bad. One problem is that while a Date instance has no time zone, its toString() method uses the JVM's default time zone to render a string. And Date's toString method uses that terrible ambiguous format.

You should avoid using java.util.Date & Calendar classes. For now use the Joda-Time library. In Java 8, you can use the new java.time.* classes.

You can convert back and forth between java.util.Date and Joda-Time. Pass a Date instance to Joda-Time constructor. To go back, call Joda-Time toDate() format.

Note that while a java.util.Date has no time zone information within it, in contrast a DateTime object does have a time zone assigned. If you want UTC/GMT, specify DateTimeZone.UTC.

Your code should look more like:

java.util.Date date = object.get("createDate");
DateTime createDateTime = new DateTime( date, DateTimeZone.forId( "Asia/Manila" ) );
System.out.println( createDateTime );
… do some work …
java.util.Date dateGoingBackToMongoDB = createDateTime.toDate();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!