Skip to content

Ruby Time serialisation

Guy Boertje edited this page Jan 8, 2015 · 3 revisions

TL;DR set the TZ environment variable for the JVM if you want consistent serialized strings. e.g. TZ=UTC jirb

With v 0.2.8 you can supply a DateTime format and timezone options to JrJackson See the tests for details.

Please be aware of the following:

Using MRI 2.1.3 and JRuby 1.7.17 Java version "1.7.0_65"

MRI

et = Time.parse('2014-06-10 18:18:40 EDT')
et.to_f
  => 1402438720.0
et.to_s
  => "2014-06-10 23:18:40 +0100"
et.zone
  => "BST"

ut = Time.parse('2014-06-10 18:18:40 EDT').utc
ut.to_f
  => 1402438720.0
ut.to_s
  => "2014-06-10 22:18:40 UTC"
ut.zone
  => "UTC"
JRuby

et = Time.parse('2014-06-10 18:18:40 EDT')
et.to_f
  => 1402438720.0
et.to_s
  => "2014-06-10 23:18:40 +0100"
et.zone
  => 'BST'

ut = Time.parse('2014-06-10 18:18:40 EDT').utc
ut.to_f
  => 1402438720.0
ut.to_s
  => "2014-06-10 22:18:40 UTC"
ut.zone
  => "UTC"

BUT

MRI

TZ=America/Toronto irb -r time
et = Time.parse('2014-06-10 18:18:40 EDT')
et.to_f
  => 1402438720.0
et.to_s
  => "2014-06-10 18:18:40 -0400"
et.zone
  => "EDT"

AND

JRuby

TZ=America/Toronto jirb -r time

et = Time.parse('2014-06-10 18:18:40 EDT')
et.to_f
  => 1402438720.0
et.to_s
  => "2014-06-10 18:18:40 -0400"
et.zone
  => "EDT"

This gives the same Float but a different String representation for object et.

HOWEVER in either Ruby with or without TZ set, using Time new

mt = Time.new(2014,6,10,18,18,40, "-04:00")
mt.to_f
  => 1402438720.0
mt.to_s
  => "2014-06-10 18:18:40 -0400"
mt.zone
  => nil

Weird that the zone method returns nil but the to_s method somehow knows that object's string representation is for the EST zone

This does not happen with Time parse class method, although I suspect that everyone thinks/hopes that it did.

Now I am tempted to say: JrJackson users beware the origin of your Time instances and how they are created

However, in JrJackson, by calling the to_time method, a new Time instance is returned in the default VM timezone. Bummer! This looks like a Ruby bug.

It gets more weird. Based on object_ids, Date instance to_date returns self as does DateTime to_datetime, but Time to_time returns a new object.

Conclusion

In all the above cases time string representations can be parsed back to the same Float value and that is what is important.

Clone this wiki locally