Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java says these 2 Date objects are not equal

Tags:

java

date

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().

like image 459
pacoverflow Avatar asked Dec 27 '22 14:12

pacoverflow


1 Answers

The third println() prints getTime() of the wrong object:

System.out.println("newDate=" + newDate + "; gettime=" + date.getTime());
                                                         ^^^^ should be newDate

I suspect that once you print out newDate.getTime(), you'll discover that it differs from date.getTime().

like image 71
NPE Avatar answered Jan 04 '23 21:01

NPE