Happy
Happy

Reputation: 77

How to compare date in Groovy?

I need to compare two data in format 13.07.2017 14:03:51,469000000 using groovy

I try to do this, but get error message.

I get next data:

time1 = 13.07.2017 14:03:51,469000000

time2 = 13.07.2017 14:03:52,069000000

Then I try to compare it:

time1  = time1['TIME'] as String
time2  = time2['TIME'] as String
assert time1 > time2, 'Error'

Which type of value should I choose for date for compare it?
Whats wrong in my comparing?

Upvotes: 0

Views: 31876

Answers (1)

Rao
Rao

Reputation: 21369

You need to convert the string to Date and then compare as shown below.

In order to convert, the right date format should be used.

Here you go, comments inline:

//Define the date format as per your input
def df = "dd.MM.yyyy HH:mm:ss,S"

//Parse the date string with above date format
def dateTime1 = new Date().parse(df, "13.07.2017 14:03:51,469000000")
def dateTime2 = new Date().parse(df, "13.07.2017 14:03:52,469000000")

//Compare both date times
assert dateTime1 < dateTime2

Upvotes: 8

Related Questions