jupp0r jupp0r - 1 year ago 107
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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download