Rails JSON and XML Serialization Include Microseconds

Can microseconds be included when serializing a Rails object for datetime fields? For instance:

{ 
  "created_at":"2011-05-27T19:49:43.123456Z", 
  "updated_at":"2011-05-27T19:49:43.654321Z", 
  "..."
}
+3
source share
1 answer

You need to override the default JSON formatting that is installed in this file . The format you want to use will be as follows:

strftime('%Y/%m/%d %H:%M:%S.%6N %z')

And you can fix JSON DateTime output like this

class DateTime
  def as_json(options = nil)
    strftime('%Y/%m/%d %H:%M:%S.%6N %z')
  end
end

And here is the link to the fractional time references available in strftime ()% N - Fractional seconds, defaults to 9 digits (nanosecond)

%3N millisecond (3 digits)
%6N microsecond (6 digits)
%9N nanosecond (9 digits)
+1
source

All Articles