I am using Gson to convert a java.util.Date object into Json and then converting the Json back into a java.util.Date object:
Date date = new Date();
System.out.println("date=" + date + "; date.getTime()=" + date.getTime());
String json = gson.toJson(date);
System.out.println("date in json format=" + json);
Date newDate = gson.fromJson(json, Date.class);
System.out.println("newDate=" + newDate + "; gettime=" + date.getTime());
if (!newDate.equals(date)) {
System.out.println("dates are not the same - bad");
}
else
System.out.println("dates are the same - good");
The 2 Date objects should be equal, but as you can see from the output, they are not:
date=Fri Nov 23 12:18:21 EST 2012; date.getTime()=1353691101023
date in json format="Nov 23, 2012 12:18:21 PM"
newDate=Fri Nov 23 12:18:21 EST 2012; gettime=1353691101023
dates are not the same - bad
How can the Date objects be different, when the Javadoc for the Date.equals() method says “two Date objects are equal if and only if the getTime method returns the same long value for both”? As you can see from the output, both Date objects return the same value for getTime().
The third
println()printsgetTime()of the wrong object:I suspect that once you print out
newDate.getTime(), you’ll discover that it differs fromdate.getTime().