Nav & Search

Parsing dates from RSS-feeds to Groovy Date-objects in Grails

Projects

During my work with thurst.net i recently got into a snag when I tried to parse the publication dates from the RSS-posts and save them as Groovy-dates. After many checks and double-checks of the format for the parsing, I could’t understand why the Date.parse() function crashed and complained that there was something wrong with the format. I got closer to the solution when I tried parsing a date consisting of only numbers, since it worked I knew that the code parsing the string was correct.

I realized the real problem when I printed the current date using RSS-formatting:

println new Date().format('EEE, d MMM yyyy HH:mm:ss Z')

The output said: “to, 3 sep 2009″, which is the correct format but in Swedish. I then tried to parse a swedish date using:

println new Date().parse('EEE, d MMM yyyy', 'to, 3 sep 2009').format('EEE, d MMM yyyy HH:mm:ss Z')

And since I got a nice date I without a crash I knew that I just had to find a way to get the parser to understand English dates. Turns out the default locale can be changed using:

Locale.setDefault(Locale.ENGLISH)

and for an application-wide change that line is added to BootStrap.groovy.

Reference

Groovy Dates

Groovy JDK Date Reference



Leave a comment

Your email will not be published.

*