2

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()
user2864740
  • 60,010
  • 15
  • 145
  • 220
kaskelotti
  • 4,709
  • 9
  • 45
  • 72

1 Answers1

2

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

Haim Raman
  • 11,508
  • 6
  • 44
  • 70
  • 1
    Thanks for the confirmation that my logic is correct and there actually is something with JsonBuilder. Instead of custom formatting, I decided to change the underlying JSON lib, thanks for the idea though. Btw, `Jacson` fails on the same problem, but `Jacson-jr` works fine. – kaskelotti Sep 10 '14 at 06:44