Krishna
Krishna

Reputation: 157

Java Date comparison: Dates in different formats

I have two dates in String format as: say String date1 = 2018-08-29 and in ISO-OFFSET_DATE_TIME format as String date2 = 2018-08-30T00:00:00+10:00. What is the best way to compare date1 and date2 for equality? I am not concerned about time, only day, year and month matters. Should I be converting them to instant and compare?

Upvotes: 2

Views: 8113

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338835

tl;dr

LocalDate
.parse( "2018-08-29" ) 
.isEqual(
    OffsetDateTime
    .parse( "2018-08-30T00:00:00+10:00" )
    .toLocalDate()
)

false

java.time

Parse each input during its appropriate type in java.time.

LocalDate ld = LocalDate.parse( "2018-08-29" ) ;
OffsetDateTime odt = OffsetDateTime.parse( "2018-08-30T00:00:00+10:00" ) ;

Compare by extracting a LocalDate from the OffsetDateTime.

Boolean sameDate = ld.isEqual( odt.toLocalDate() ) ;

false

Or perhaps you want to adjust that OffsetDateTime from its offset of ten hours ahead of UTC to another offset or time zone. For example, let’s adjust back to UTC before extracting a date to compare.

LocalDate
.parse( "2018-08-29" ) 
.isEqual(
    OffsetDateTime
    .parse( "2018-08-30T00:00:00+10:00" )
    .withOffsetSameInstant( ZoneOffset.UTC )
    .toLocalDate()
)

This changes our results from false, seen in code above, to true.

true

Upvotes: 3

Anonymous
Anonymous

Reputation: 86296

If this is the only thing you will ever want to know about the two strings:

    LocalDate ld1 = LocalDate.parse(date1);
    LocalDate ld2 = LocalDate.parse(date2, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    if (ld1.isEqual(ld2)) {
        System.out.println("They are the same date");
    } else {
        System.out.println("They are different dates");
    }

Output using your string examples frmo the question:

They are different dates

I was just writing code similar to that by Basil Bourque when his answer came. I prefer to handle date and time by the correct date-time objects, which is exactly what he’s doing. By parsing date2 into an OffsetDateTime you are keeping all information, and the conversion to LocalDate for comparison is easy. For most purposes I recommend that way.

Only if you know for sure that you will never need the time of day, you may take a shortcut. You may of course use the fast way by JunJie Wang. I prefer my own code above, though, for two reasons: I tells the reader clearly that the strings are dates and times and handles them correctly as such. And it thereby also provides validation of the string formats. If some day by accident you get a completely different string, you will be notified through a DateTimeParseException.

Upvotes: 0

JunJie Wang
JunJie Wang

Reputation: 470

the fastest way is;

String date1 = "2018-08-29";
String date2 = "2018-08-30T00:00:00+10:00";
boolean isEqual = date2.startsWith(date1);

Upvotes: 3

Related Questions