My timestamps are coming out in my json responses like "created_at":"2014-07-07T18:01:26.000Z" when I'd really prefer all timestamps in iso8601 format. Is there a way to set this for all my serializers?
fyi... Time.now.to_json does give me iso8601 in my rails console.
Thanks for any help!
AMS use TimeWithZone#as_json for the datetime field. so make it work as u expect.
Not sure if this is a good idea but I've done something like this in the past:
class ApplicationSerializer < ActiveModel::Serializer
def attributes
super.transform_values do |value|
value = value.iso8601 if value.respond_to?(:iso8601)
value
end
end
end
In Rails 4.1, you can specify:
ActiveSupport::JSON::Encoding.time_precision = 0
Unfortunately, in Rails 4.0, you have to monkey patch:
# config/initializers/time_as_json.rb
module ActiveSupport
class TimeWithZone
def as_json(options = nil)
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
xmlschema
else
%(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
end
end
end
end
@bradly do the above replies resolve your issue?
@jdjkelly Yes. @bryanrite's solution worked great. I'm closing this. Thanks everyone!
Adding the commit for future reference: https://github.com/rails/rails/commit/28ab79d7c579fa1d76ac868be02b38b02818428a.
:+1:
We can also override read_attribute_for_serialization.
def read_attribute_for_serialization(attr)
value = super
if value.kind_of?(ActiveSupport::TimeWithZone)
# change format
end
value
end
Most helpful comment
In Rails 4.1, you can specify:
Unfortunately, in Rails 4.0, you have to monkey patch: