Convert Java Instant to String with timezone

499 views Asked by At

I have to compare a instant with a date String but format are differents.

The Instant is initiate with "now" but without "+nnnn" part (I think it's timezone).

How can I create a Instant and convert it to String with this format for compare with my String ?

String :  2022-04-30T07:41:36.413+0000
Instant : 2022-04-30T07:41:36.413Z
1

There are 1 answers

2
Basil Bourque On

Think in terms of objects, not text. Date-time objects have their own internal implementations of the date-time values they represent. So tte have no “format” because that are not mere strings.

Parse your input text as an OffsetDateTime using DateTimeFormatter. This has been covered many many times already on Stack Overflow. Search to learn more.

From that OffsetDateTime object, extract an Instant.

Instant myInstant = myOffsetDateTime.toInstant() ;

Compare that Instant with the current moment.

boolean isInThePast = myInstant.isBefore( Instant.now() ) ;

Notice that no text is involved. The objects do the heavy lifting for us, rather than us doing string manipulations and comparisons.