Using Joda-Time to form correct ISODate for Mongo insert

Your input string format is correct, as long is that is intended to represent UTC.

Change your parser to use the one that matches this format:

DateTimeFormatter parser = ISODateTimeFormat.dateTime();

The rest of your question doesn't make much sense to me. You shouldn't pass the parser, but rather the return value from parseDateTime, which you don't appear to be capturing.

DateTime result = parser.parseDateTime(crDt);

mongo.setCrDt(recordId, result.toDate());

Whether or not that last line will work depends on what that function accepts.


I solved this by adding an "Encoding Hook" in the constructor of the Service class where I do the updates to MongoDB. This will allow you to use org.joda.time.DateTime in your code and that will be saved as java.util.Date in MongoDB.

MyService.java

@Inject
public MyService(com.mongodb.Client client) {
      BSON.addEncodingHook(DateTime.class, new JodaTimeTransformer());
      BSON.addDecodingHook(Date.class, new JodaTimeTransformer());
      this.mongoClient = mongoClient;
}

JodaTimeTransformer.java

import java.util.Date;

import org.joda.time.DateTime;

public class JodaTimeTransformer implements org.bson.Transformer {

    @Override
    public Object transform(Object o) {
        if(o instanceof DateTime) {
            return ((DateTime)o).toDate();
        }
        else if(o instanceof Date) {
            return new DateTime((Date) o);
        }
        throw new IllegalArgumentException("JodaTimeTransformer can only be used with DateTime or Date");
    }

}

The answer by Matt Johnson is correct. But it could be even simpler: Pass the (ISO 8601) string directly to constructor of DateTime. No need for a formatter.

Pay attention to time zone. A DateTime object in Joda-Time truly knows its own assigned time zone, unlike a java.util.Date object. Do you want your DateTime object to be assigned the JVM’s default time zone, no time zone (UTC), or a specific time zone?

For a date-time assigned the default time zone.

DateTime dateTime = new DateTime( "2013-01-19T15:28:58.851Z" );

For a date-time assigned UTC/GMT (no time zone offset).

DateTime dateTime = new DateTime( "2013-01-19T15:28:58.851Z", DateTimeZone.UTC );

For a date-time assigned a specific time zone.

DateTime dateTime = new DateTime( "2013-01-19T15:28:58.851Z", DateTimeZone.forId( "Europe/Paris" ) );