mcroteau mcroteau - 5 months ago 40
Groovy Question

Groovy : Attempting to parse a date

I am attempting to parse a date string using groovy but running into issues. Here is what the string looks like and logic which isn't working.

def dateString = "2017-01-01T12:00:00Z"
def date = Date.parse("yyyy-MM-dd HH:mm:ss", dateString)


Ive also tried

def date = Date.parse("yyyy-MM-dd'T'HH:mm:ssZ", dateString)


which doesn't parse either. Any help would be most appreciated.

Thanks in advance for your help.

Answer Source

Try following format: yyyy-MM-dd'T'HH:mm:ssX

Running script:

def dateString = "2017-01-01T12:00:00Z"
def date = Date.parse("yyyy-MM-dd'T'HH:mm:ssX", dateString)
println date

Produces following output:

Sun Jan 01 13:00:00 CET 2017

Comparing yyyy-MM-dd'T'HH:mm:ss'Z' to yyyy-MM-dd'T'HH:mm:ssX

You need to consider supporting timezone offset in dates you are parsing. Check following script run with current timezone set to Europe/Warsaw:

println Date.parse("yyyy-MM-dd'T'HH:mm:ss'Z'", dateString)
println Date.parse("yyyy-MM-dd'T'HH:mm:ssX", dateString)

It will produce two different result:

Sun Jan 01 12:00:00 CET 2017
Sun Jan 01 13:00:00 CET 2017

First one treats Z as a literal and parses given date and time using current timezone. It means that when you run this script using different current timezone set, you will get again 12:00:00 in this timezone.

Second one takes timezone information into account and treats Z not as a literal, but as a GMT/UTC timezone notation. So in case of my timezone correct time is 13:00:00 and not 12:00:00.

There is also another issue with the first format. If you start receiving dates like 2017-01-01T12:00:00+0400 you will get following exception when the first pattern is used:

Caught: java.text.ParseException: Unparseable date: "2017-01-01T12:00:00+0400"
java.text.ParseException: Unparseable date: "2017-01-01T12:00:00+0400"
    at avg.run(avg.groovy:35)

Second one parses given dateString with explicit timezone offset with no issue and prints:

Sun Jan 01 09:00:00 CET 2017

which is correct date and time for my current timezone.

I hope it helps.