jupp0r jupp0r - 3 months ago 15
Ruby Question

DateTime serialization and deserialization

I'd like to serialize a Ruby DateTime object to json. Unfortunately, my approach is not symetrical:

require 'date'
date = DateTime.now
DateTime.parse(date.to_s) == date
=> false

I could use some arbitrary strftime/parse string combination, but I believe there must be a better approach.


Both the to_s method and the to_json method (provided require 'json') ignore the nanoseconds which are stored by the DateTime object date. Good old Marshal delivers:

require 'date'
date = DateTime.now
m_date = Marshal.dump(date)
p Marshal.load(m_date) == date # => true