2

I creating a custom json object with dates in it. Unfortunately when I want use the date in jQuery to turn into a Date object, the object turns to be invalid. This is the case for Date Strings like:

2011-12-14 00:59:59 +01:00

If I render it with the built in object.to_json the time gets rendered like this:

2011-12-14T00:59:59+01:00

This way I can turn this string in to a query date object.

So my question is how to render a date in rails so that it becomes the second format.

Thanks Markus

3 Answers 3

2

As far i can see from the sources, the to_json method of DateTime is add by ActiveSupport (source here).

So you should monkey patch it in an initializer (such as config/initializers/datetime.rb) like this:

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

Tested and working here: http://codepad.org/NRzqiJT3

0
0

The following will work in all major browsers and ie7+ (I haven't tested ie6) if put in an initializer (e.g. config/initializers/)

class ActiveSupport::TimeWithZone
  def as_json(options = {})
    strftime('%Y/%m/%d %H:%M:%S %z')
  end
end
0

Here's another way to achieve similar goal:

class Date
  def as_json(options = {})
    I18n.localize self
  end
end

Hope it helps somebody.

1
  • Seems to be a neat solution. Thanks.
    – Fenix
    Feb 9, 2017 at 7:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.