-2

i have this Date String 2020-07-26T20:08:27Z i want to perform date comparison.

so is there any framework/util for this operation.

String s1 = "2020-07-26T20:08:27Z";
String s2 = "2020-07-26T21:08:27Z";

in the above sample code, i want to find the bigger date

Naman
  • 27,789
  • 26
  • 218
  • 353
user2587669
  • 532
  • 4
  • 10
  • 22

1 Answers1

2

tl;dr

Instant
.parse( "2020-07-26T20:08:27Z" ) 
.isBefore(
    Instant.parse( "2020-07-26T21:08:27Z" )
)

true

java.time

Use the modern java.time classes built into Java 8 and later.

ISO 8601

The Z on the end of your input indicates an offset-from-UTC of zero hours-minutes-seconds, or UTC itself. The Z is pronounced “Zulu”.

Your input strings are in standard ISO 8601 format. The java.time classes use these formats by default when parsing/generating strings. So no need to specify a formatting pattern.

Instant

An Instant object represents a moment in UTC.

Instant instantA = Instant.parse( "2020-07-26T20:08:27Z" ) ;
Instant instantB = Instant.parse( "2020-07-26T21:08:27Z" ) ;

Compare using equals, isBefore, isAfter.

boolean aBeforeB = instantA.isBefore( instantB ) ;

Duration

You can capture the time elapsed between the two moments as a Duration object.

Duration d = Duration.between( instantA , instantB ) ;

You can ask the Duration object if it is zero or negative.


Table of all date-time types in Java, both modern and legacy

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154