You have to override ActiveSupport::TimeWithZone#as_json
. For example, using Rails instead of Sinatra:
# new file config/initializers/timestamp_serialization.rb
class ActiveSupport::TimeWithZone
def as_json(options = nil)
time.strftime("%Y-%m-%d %H:%M:%S")
end
end
The reason for this is that the source as_json
method only accepts two possibilities: iso8601 enabled, in which case it uses iso8601
, or iso8601 disabled, in which case it uses "%Y/%m/%d %H:%M:%S"
:
# File activesupport/lib/active_support/time_with_zone.rb, line 176
def as_json(options = nil)
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
xmlschema(ActiveSupport::JSON::Encoding.time_precision)
else
%(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
end
end
(note: xmlschema
is an alias for iso8601
)
I ran into this while running an upgrade from Rails 3.2 to 4.0, which had the side effect of changing all the serialized timestamps from 0-digit precision ISO 8601 format to 3-digit precision. Unfortunately, Rails only lets you configure the precision by itself starting at 4.1, so I had to override the method entirely.