12

I'm using JBuilder to render the views of the JSON API part of my application. The problem I'm running into is that my DateTimes are being rendered like this:

"2013-07-02T17:03:18.000Z"

...when what I really want is this:

"2013-07-02T17:03:18Z"

I'm not sure where those decimals are coming from...

I'm rendering the field in the typical JBuilder way:

json.my_datetime_field

I have a date format initializer in my app:

Date::DATE_FORMATS[:default] = '%Y/%m/%d %Z'
Time::DATE_FORMATS[:default] = '%Y/%m/%d %H:%M:%S %Z'
Date::DATE_FORMATS[:month_day_year] = '%m-%d-%Y'

However, this doesn't seem to impact JBuilder, and that is good. I want ISO8601 format coming from my API. I'm on Rails 4.0.0 final, by the way.

elsurudo
  • 3,579
  • 2
  • 31
  • 48
  • 1
    Not sure about JBuilder's settings, but FYI - fractional second decimals are allowed in ISO8601. 3 places are common, but so are 6 or 7 places. – Matt Johnson-Pint Jul 03 '13 at 14:53
  • Yeah, I caved and changed my client-side parser's date formatter to allow for fractional seconds. I'll leave this question here in case anyone knows how to actually change jbuilder's output. The closest I've come is monkey-patching DateTime to return what I want with "as_json", but that seems really hacky. – elsurudo Jul 04 '13 at 13:12

3 Answers3

11

using under rails? to avoid encode with float, run this method on initialize block on your project

ActiveSupport::JSON::Encoding.time_precision = 0
shao1555
  • 126
  • 1
  • 3
4

I've experienced this while trying to render a format more amenable to iPhone applications. You could use the .strftime method.

json.my_datetime_field(object.timestamp.strftime('%Y/%m/%d %H:%M:%S %Z'))

will create a json field called my_datetime_field

{ "my_datetime_field": timestamp_goes_here  }
OneChillDude
  • 7,856
  • 10
  • 40
  • 79
1

This work for me.

/view/api/earthquakes/index.json.jbuilder

json.array!(@earthquakes) do |earthquake|
  json.extract! earthquake, :id,
                :name,
                :magnitude,
                :lat,
                :lon,
                :city,
                :region,
                :state,
                :country,
                :usgs_id,
                :usgs_url,
                :usgs_url_detail,
                :num_structures

  json.date(earthquake.date.strftime('%Y-%m-%d %H:%M:%S %Z'))

end
OhBeWise
  • 5,350
  • 3
  • 32
  • 60