Rails: always include the milliseconds with created_at for every model

For Rails 4.1 and above you can set the time_precision, e.g. in application.rb

ActiveSupport::JSON::Encoding.time_precision = 3

By the way, showing the milliseconds is now the default, it can be set to 0 if they should be omitted. Also it's good to know that .iso8601 doesn't include milliseconds but .as_json preserves them.


Overriding ActiveSupport::TimeWithZone#as_json worked for me:

class ActiveSupport::TimeWithZone

  def as_json(options = nil)
    if ActiveSupport::JSON::Encoding.use_standard_json_time_format
      xmlschema(3)
    else
      %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
    end
  end

end

Make sure to put this code in a file that is required by your Rails app. Now when I convert a created_at attribute to JSON, I get the milliseconds:

puts Post.last.created_at.to_json
# => "2012-06-29T11:51:00.841Z"

Also make sure to use Time.zone to instantiate new Time objects so that they show the same JSON behavior:

time = Time.zone.now
puts time.to_json
# => "2012-06-29T16:45:30.547Z"

Hope this helps someone!