My code:
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
...
public void testDateSerializer() {
final Date date = new Date();
log.info("Today's date: " + date + " and date.getTime()=" + date.getTime());
final JSONObject jsonObjectForDate = (JSONObject) JSONSerializer.toJSON(date);
log.info("Same date expressed in json: " + jsonObjectForDate.toString());
}
The output:
INFO - 2011-08-13 22:12:04,938 - TestJsonConversion.testDateSerializer(52) | Today's date: Sat Aug 13 22:12:04 EDT 2011 and date.getTime()=1313287924927
INFO - 2011-08-13 22:12:05,216 - TestJsonConversion.testDateSerializer(55) | Same date expressed in json: {"date":13,"day":6,"hours":22,"minutes":12,"month":7,"seconds":4,"time":1313287924927,"timezoneOffset":240,"year":111}
My questions:
- Why year=111. We are still in 2011 unless I missed something!
- I am on US ETD, so offset is -4 hours, not +240, which, even expressed in minutes is still wrong regarding the sign of the offset.
So what am I doing wrong? Is this a bug in the library? If so, what library should I use to accomplish the same conversion?
Thank you
Actually this behavior is completely expected, believe it or not.
You are using the class
java.util.Date. This class has mostly a bunch of deprecated methods. See the documentation here:http://download.oracle.com/javase/6/docs/api/java/util/Date.html
Now your JSON serializer is just going to make a JSON string out of the getters in your Java object. Take a look at the getters in the
java.util.Dateclass. Most are deprecated and you can see why. The year is relative to 1900! The time zone offset is in minutes backwards.To make your application work the way you would expect, check out the deprecation warnings for
Datewhich tell you to useGregorianCalendar. However, I recommend using JodaTime. A little learning curve, but this is so worth it.