MongoDB date time insertion is not happening perfectly from java

526 Views Asked by At

I am running the code in my local machine. The mongoDb is also running in the local. So there should be no issue in timezone if I am not wrong. I am writing this:

DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateHourMinuteSecond();
LocalDateTime date=new LocalDateTime();
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeFormatter.print(date));

BasicDBObject basicDBObject = new BasicDBObject();
      basicDBObject.put("batchId",batchId);
      basicDBObject.put("batchStatus",BatchStatus.STARTED.toString() );

        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>: "+ date.toString());
        basicDBObject.put("startTime",dateTime.toDate());

 mongoTemplate.getCollection(collectionName).insert(basicDBObject);

The sysout is printing 2016-12-23T11:24:54.907. In db I am getting 2016-12-23 05:54:54.000Z. Can anyone help?

Thanks, Sumit.

1

There are 1 best solutions below

0
On

Mongo store time as UTC time, set Timezone to local in your program.

LocalDateTime localtDateAndTime = LocalDateTime.now(ZoneId.of("Australia/Sydney"));