I am having trouble doing a date comparison.
I am using Groovy and Spock to write an integration test against a web service.
The test is to first use the web service to create a Thing
, then immediately make another call to get the details of the Thing
by its ID. I then want to verify that the CreatedDate
of the thing is greater than a minute ago.
Here is some JSON of the call
{
"Id":"696fbd5f-5a0c-4209-8b21-ea7f77e3e09d",
"CreatedDate":"2017-07-11T10:53:52"
}
So, note no timezone information in the date string; but I know it is UTC.
I'm new to Java (from .NET) and a bit bamboozled by the different date types.
This is my Groovy model of the class, which I use Gson to deserialize:
class Thing {
public UUID Id
public Date CreatedDate
}
The deserialization works fine. But the code, which runs in a non-UTC time zone thinks that the date is actually in the local time zone.
I can create a variable representing "1 minute ago" using the Instant
class:
def aMinuteAgo = Instant.now().plusSeconds(-60)
And this is how I am trying to do the comparison:
rule.CreatedDate.toInstant().compareTo(aMinuteAgo) < 0
The trouble is, the runtime thinks that the date is local time. There appears to be no overload for me to force .toInstant()
into UTC.
I've tried using what I understand to be more modern classes - such as LocalDateTime
and ZonedDateTime
in my model instead of Date
, however Gson doesn't play nice with the deserialization.