Removing milliseconds in JSON under ActiveRecord 4.0

Rails 4.0 introduced a small bug in JSON generation with this pull request. The output format for times (ActiveRecord::TimeWithZone) in JSON changed to include milliseconds. Sounds good right? Well, not if your API clients crash trying to parse milliseconds. Unfortunately, Rails 4.0 didn’t provide a configuration option for the timestamp precision in JSON output. What is a programmer under the gun to do? Upgrade to Rails 4.1 or get out your monkey and your patch and get to work?


First, lets see the bug in action. This test passes in Rails 3.2.15, but fails in Rails 4.0.4:

Simple enough. This is easier to see if you’ve got a Rails app:

Rails 4.1 adds a configuration option to default the time precision. In that version, you can set ActiveSupport::JSON::Encoding.time_precision = 0. However, if you are on Rails 4.0 for a bit, you can monkey patch AtiveSupport::TimeWithZone to go back to the Rails 3.2 implementation:

Normally, it seems the Rails team does a better job than this. Fortunately, with Ruby we’ve got the openness to go back to the old behavior in a pinch.

3 thoughts on “Removing milliseconds in JSON under ActiveRecord 4.0”

Leave a Reply

Your email address will not be published. Required fields are marked *