Monday, April 7, 2014

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.


  1. Thanks a bunch, hit this exact issue on upgrade and ios app order was wrong!

  2. Thanks for this post, you saved my bacon! I searched for over an hour trying to find where that time precision setting was in Rails 4.1. You be the man!

  3. Thanks! Very helpful!