How do I modify my Rails app to always include the milliseconds information with the created_at
field of my models?
This question has the answer for how to do it for an individual model, but I want to do it globally.
For example, when I retrieve all my Item
models (by hitting /items
with a GET), I get the following JSON:
[{"created_at":"2011-08-07T23:42:15Z","updated_at":"2011-08-07T23:42:15Z","id":180,"user_id":6,"content":"test"}]
But note that the created_at
field doesn't have any information about the millisecond that it was created. How do I include that for all my models?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With