简体   繁体   中英

Mongo Db date time insertion

I am newer in mongoDb trying to insert current date time using Java program. I am using joda library to to format the date into ISOdate format and want to store the current date and time as it is.But after doing insertion it is showing 1 hour delay time from my current time in data base.

Here is my code.

    DateTimeFormatter parser=ISODateTimeFormat.dateHourMinuteSecond();
    Instant inst=new Instant();
    DateTime result=parser.parseDateTime(parser.print(inst));
    dbObject.put(KeyConstants.CREATED_ON,result.toDate());
    dbObject.put(KeyConstants.UPDATED_ON,result.toDate());
    collection.insert(dbObject); 

I am inserting current date and time :ISODate("2014-08-01T05:58:14Z")
But in data base it showing : ISODate("2014-08-01T06:58:14Z")

Wahid, its happening because the date created out of

result.toDate() 

is date with local timezone.

for example:

DateTimeFormatter parser=ISODateTimeFormat.dateHourMinuteSecond();      
DateTime result=parser.parseDateTime("2014-07-29T07:23:06");
System.out.println(result.toDate());

the result date is in

Tue Jul 29 07:23:06 IST 2014

which is as per my local timezone. And MongoDB stores date from epoch.

Add following code before result.toDate()

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

It will create UTC date.

You can refer date document to know about dates in mongoDB Hope so this might help you.

Thanks for help Ninad,

I got sorted that problem the below code is inserting current date and time inside the data base as it is.

DateTimeFormatter parser=ISODateTimeFormat.dateHourMinuteSecond();
LocalDateTime dt=new LocalDateTime();
LocalDateTime result=parser.parseLocalDateTime(parser.print(dt));
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
dbObject.put("CREATED_ON",result.toDate());
dbObject.put("UPDATED_ON",result.toDate());

Regards : Wahid

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