kaskelotti
kaskelotti

Reputation: 4832

How to keep timezones when using Groovy's JsonBuilder?

Groovy's JsonBuilder does not seem to transform timezones in dates to JSON string at all. Or more precisely, it uses GMT always. For example the following code should print the date as midnight of 2001-02-03, GMT +2. But instead, it prints 2001-02-02T22:00:00+0000, i.e. the same date minus 2 hours as if it would be in GMT.

Is there a bug in JsonBuilder or is this a "known feature" that I need to take into account while using the API?

import groovy.json.JsonBuilder

def c = new GregorianCalendar( new Locale( "fi", "FI" ) ) // GMT+2, no DST by default
c.set( 2001, 1, 3, 0, 0 ) // 2001-02-03T00:00:xx, xx is current seconds. Not set as irrelevant


println ( new JsonBuilder( [ date: c.getTime() ] ) ).toString()

Upvotes: 2

Views: 933

Answers (1)

Haim Raman
Haim Raman

Reputation: 12043

Looking at the JsonBuilder it looks like a bug or unsupported functionality.

When calling

( new JsonBuilder( [ date: c.getTime() ] ) ).toString()

It calls statically JsonOutput.toJson(content). After some logic it calls JsonOutput.writeObject that figures out we are dealing with date (or calendar if you omit the getTime call).

Then it calls JsonOutput.writeDate which refers to a private static dateFormatter Based on DateFormatThreadLocal();

DateFormatThreadLocal creates SimpleDateFormat with US locale and GMT time zone.

I could not find any way to specify your own Date format to the builder, so I suggest you will pre-format dates and provide them as string to the builder:

 def fiTimeZone = TimeZone.getTimeZone("GMT+2")
 def formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", new Locale( "fi", "FI" ))
 formatter.setTimeZone(fiTimeZone)

 def c = new GregorianCalendar( new Locale( "fi", "FI" ) ) 
 c.set( 2001, 1, 3, 0, 0 ) // 2001-02-03T00:00:xx, xx is current seconds. Not set as irrelevant
 def formatedDate = formatter.format(c.getTime())
 println ( new JsonBuilder( [ date: formatedDate ] ) )

output {"date":"2001-02-03T00:00:42+0200"}

Mind thread safety issues with SimpleDateFormat see here

Upvotes: 2

Related Questions