title: Inserting Date in MongoDB using Java
body: <p>I have a REST service in Dropwizard which stores data from client to MongoDB and queries MongoDB for realtime analysis on Dashboard.</p>
  
  <p>From client side i get JSON of Key-Value pair, in which i have a date string as follow :</p>
  
  <pre><code>2014-07-14T05:58:20
  </code></pre>
  
  <p>and timezone as follow :</p>
  
  <pre><code>"Asia/Kolkata"
  </code></pre>
  
  <p>I have to keep all document in mongodb in UTC.</p>
  
  <p>I want to convert the dates to UTC according to their timezone and store.</p>
  
  <p>I am using JodaDate to do so</p>
  
  <pre><code>DateTimeFormatter formatterInstance = DateTimeFormat
                          .forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(
                                  DateTimeZone.forID(timeZone));
                  dateInstance = formatterInstance.parseDateTime(timeString);
  DateTime dtTz = dateInstance.withZone(DateTimeZone.UTC);
  </code></pre>
  
  <p>but when i try to save DateTime in mongoDB it gives following error</p>
  
  <pre><code>Exception in thread "main" java.lang.IllegalArgumentException: can't serialize class org.joda.time.DateTime
  at org.bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:270)
  at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:174)
  at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:120)
  at com.mongodb.DefaultDBEncoder.writeObject(DefaultDBEncoder.java:27)
  at com.mongodb.OutMessage.putObject(OutMessage.java:289)
  at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:261)
  at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:226)
  at com.mongodb.DBCollection.insert(DBCollection.java:75)
  at com.mongodb.DBCollection.insert(DBCollection.java:59)
  at com.mongodb.DBCollection.insert(DBCollection.java:104)
  at com.datedemo.main.TimeZoneManager.getUTCTime(TimeZoneManager.java:65)
  at com.datedemo.main.DateExample.main(DateExample.java:22)
  </code></pre>
  
  <p>Uptill now i was storing dates in Milliseconds DateTime.getMillis() in NumberLong() but for some queries like aggregation on day, month for LineChart display its difficult to deal with longNumber.</p>
  
  <p>Please suggest any alternate ways so that all the Dates are stored in UTC as per their Timezone.
  i want to avoid any conversion of Date by the REST service local timezone.</p>