1

I don't want default json format of Active Support. So I put code in app.rb of my project. ActiveSupport::JSON::Encoding.use_standard_json_time_format = false

it changed time format from iso8601 to strftime('%Y/%m/%d %H:%M:%S %z'). But i want to change time format strftime('%Y-%m-%d %H:%M:%S %z').

Time.now.to_json => output "2016/06/20 10:57:43 +0300" but i want to format "2016-06-20 10:57:43 +0300"

My project is a Ruby on Sinatra.

sozgur
  • 21
  • 4

2 Answers2

0

Where do you put your code?

ActiveSupport::JSON::Encoding.use_standard_json_time_format = false

Please try: https://stackoverflow.com/a/18360367/2245697

Community
  • 1
  • 1
Tan Nguyen
  • 3,281
  • 1
  • 18
  • 18
0

You have to override ActiveSupport::TimeWithZone#as_json. For example, using Rails instead of Sinatra:

# new file config/initializers/timestamp_serialization.rb

class ActiveSupport::TimeWithZone
  def as_json(options = nil)
    time.strftime("%Y-%m-%d %H:%M:%S")
  end
end

The reason for this is that the source as_json method only accepts two possibilities: iso8601 enabled, in which case it uses iso8601, or iso8601 disabled, in which case it uses "%Y/%m/%d %H:%M:%S":

# File activesupport/lib/active_support/time_with_zone.rb, line 176
def as_json(options = nil)
  if ActiveSupport::JSON::Encoding.use_standard_json_time_format
    xmlschema(ActiveSupport::JSON::Encoding.time_precision)
  else
    %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
  end
end

(note: xmlschema is an alias for iso8601)

I ran into this while running an upgrade from Rails 3.2 to 4.0, which had the side effect of changing all the serialized timestamps from 0-digit precision ISO 8601 format to 3-digit precision. Unfortunately, Rails only lets you configure the precision by itself starting at 4.1, so I had to override the method entirely.

Milo P
  • 1,377
  • 2
  • 31
  • 40