[java] Comparing two joda DateTime instances

I have a problem with the comparing two DateTime objects.

System.out.println(response.getCreationDate().toString()); // will return "2013-12-31T22:59:21.000+01:00", but...  assertThat(response.getCreationDate(), equalTo(new DateTime("2013-12-31T22:59:21+01:00"))); // will throw an assertation error with the following error  Expected: <2013-12-31T22:59:21.000+01:00>  but: was <2013-12-31T22:59:21.000+01:00> 

Anyone has an idea what am I missing here?

Btw, if you are wondering why the DateTime is displayed in GMT+1:00 zone, cause that's the timezone in which I want my DateTime objects to be by default.

Thanks!

This question is related to java datetime jodatime

The answer is


DateTime inherits its equals method from AbstractInstant. It is implemented as such

public boolean equals(Object readableInstant) {     // must be to fulfil ReadableInstant contract     if (this == readableInstant) {         return true;     }     if (readableInstant instanceof ReadableInstant == false) {         return false;     }     ReadableInstant otherInstant = (ReadableInstant) readableInstant;     return         getMillis() == otherInstant.getMillis() &&         FieldUtils.equals(getChronology(), otherInstant.getChronology()); } 

Notice the last line comparing chronology. It's possible your instances' chronologies are different.


This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.


Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with datetime tag:

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")? How do I filter date range in DataTables? Convert a string to datetime in PowerShell How to insert current datetime in postgresql insert query How to change the datetime format in pandas Pandas: Subtracting two date columns and the result being an integer finding first day of the month in python Error in MySQL when setting default value for DATE or DATETIME How to Extract Year from DATE in POSTGRESQL java.time.format.DateTimeParseException: Text could not be parsed at index 21 How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds? Is there a simple way to increment a datetime object one month in Python? Pandas: Convert Timestamp to datetime.date How to insert date values into table In Oracle SQL: How do you insert the current date + time into a table? Getting today's date in YYYY-MM-DD in Python? What's the difference between Instant and LocalDateTime? How to convert string to datetime format in pandas python? What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types Format datetime to YYYY-MM-DD HH:mm:ss in moment.js How to convert an Instant to a date format? Python - Get Yesterday's date as a string in YYYY-MM-DD format python pandas extract year from datetime: df['year'] = df['date'].year is not working Create a day-of-week column in a Pandas dataframe using Python datetime to string with series in python pandas How to get current time in python and break up into year, month, day, hour, minute? How to force the input date format to dd/mm/yyyy? What exactly does the T and Z mean in timestamp? How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query How do I get the current timezone name in Postgres 9.3? Datetime current year and month in Python How to convert datetime to integer in python Convert Pandas Series to DateTime in a DataFrame Extract time from moment js object Get current date in DD-Mon-YYY format in JavaScript/Jquery Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8) How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe? Calculate time difference in minutes in SQL Server Convert Pandas Column to DateTime Inserting created_at data with Laravel

Questions with jodatime tag:

Comparing two joda DateTime instances How to format Joda-Time DateTime to only mm/dd/yyyy? Joda DateTime to Timestamp conversion How to find difference between two Joda-Time DateTimes in minutes Convert LocalDate to LocalDateTime or java.sql.Timestamp String to LocalDate Converting a date string to a DateTime object using Joda Time library Convert from java.util.date to JodaTime Number of days between two dates in Joda-Time Difference in days between two dates in Java? How to serialize Joda DateTime with Jackson JSON processor? How to get the current date and time of your timezone in Java?