active_model_serializers icon indicating copy to clipboard operation
active_model_serializers copied to clipboard

Specifing timestamp format

Open bradly opened this issue 12 years ago • 8 comments

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!

bradly avatar Jul 10 '14 19:07 bradly

AMS use TimeWithZone#as_json for the datetime field. so make it work as u expect.

zlx avatar Jul 11 '14 01:07 zlx

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

vanstee avatar Jul 15 '14 14:07 vanstee

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

bryanrite avatar Jul 15 '14 17:07 bryanrite

@bradly do the above replies resolve your issue?

jdjkelly avatar Jul 26 '14 00:07 jdjkelly

@jdjkelly Yes. @bryanrite's solution worked great. I'm closing this. Thanks everyone!

bradly avatar Aug 04 '14 19:08 bradly

Adding the commit for future reference: https://github.com/rails/rails/commit/28ab79d7c579fa1d76ac868be02b38b02818428a.

agis avatar Aug 04 '15 15:08 agis

:+1:

joaomdmoura avatar Aug 11 '15 00:08 joaomdmoura

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

dhirendra-linq avatar Jun 24 '20 05:06 dhirendra-linq