0

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
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Broshet
  • 133
  • 12
  • How do you want the timezone or time offset to be chosen? An `Instant` doesn't have a time offset built in, although in your snippet above, you've shown it in UTC. – Dawood ibn Kareem Apr 30 '22 at 07:48
  • Why are you comparing *strings*? How about converting the string to an `Instant` and comparing the `Instant`s? – Sweeper Apr 30 '22 at 08:14

1 Answers1

2

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    Ok thanks, but in complement, I have to compare Instant value with JSON content .andExpect(jsonPath("$.dateEnvoi").value(DEFAULT_DATE_ENVOI.toString())) DEFAULT_DATE_ENVOI is my instant and I need to convert it in String to compar with Json value under "dateEnvoi" tag. So I have to do it with String – Broshet Apr 30 '22 at 09:56
  • I would still prefer this the other way around: if the string from JSON can be parsed and denotes the expected value, then it is as should be. Otherwise it is not. If you do insist on comparing strings, convert the `Instant` to an `OffsetDateTime` by using its `atOffset` method (or some other way) and then format it into a string using a `DateTimeFormatter`. – Ole V.V. May 03 '22 at 08:16