Active_model_serializers: Specifing timestamp format

Created on 10 Jul 2014  路  8Comments  路  Source: rails-api/active_model_serializers

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!

Most helpful comment

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

All 8 comments

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!

:+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
Was this page helpful?
0 / 5 - 0 ratings