-1

Before I updated Rails, the default Time format the API was returning was yyyy-MM-dd'T'HH:mm:ss'Z'. Now it returns yyyy-MM-dd'T'HH:mm:ss:sss'Z'. I want to change it back due to apps that rely on the old time format. How can I change this PROJECT default format that Time::DateTime's to_s method returns?

Edit:

I should probably mention I started using the active_model_serializer gem. Not sure if that makes a difference. My guess is this change happened after the update from Rails 4.0.x to 4.1.x. Also I want to change this format for the project. This format changed between Rails versions. active_model_serializer uses to_s, so it makes more sense to override how to project sets this. I don't know where that is.

Andy
  • 10,553
  • 21
  • 75
  • 125

3 Answers3

0

You can just use strftime:

Time.now.strftime("%Y-%M-%d %H:%m:%S%Z")

one of your gems is probably overriding the DateTime to_s method. you can just override it again with you own method back

Dima
  • 8,586
  • 4
  • 28
  • 57
  • The question title states the `project Time format`. I never formatted it. It defaulted to returning `yyyy-MM-dd'T'HH:mm:ss'Z'`. – Andy Nov 20 '14 at 15:13
  • Looking at the source shows no overriding of to_s or even referencing any specific objects. Although you are not wrong you aren't answering the question. Maybe it would be helpful to tell me how to change the default to_s implementation of Time in a Rails project so it reflects all my code. If it ins't possible, well that's a different story. – Andy Nov 20 '14 at 15:35
  • you just need to create a class named `DateTime` with one method `to_s` and thats it, it will override the default DateTime to_s implementation – Dima Nov 20 '14 at 16:22
0

Maybe you need this:

# config/initializers/time_with_zone.rb

module ActiveSupport
  class TimeWithZone
    def as_json(options = nil)
      iso8601
    end
  end
end
Viktor Ivliiev
  • 1,015
  • 4
  • 14
  • 21
0

You can augment the Ruby built-in Date::DATE_FORMATS and Time::DATE_FORMATS

DATE_FORMAT = "%m/%d/%Y".freeze
TIME_FORMAT = "#{DATE_FORMAT} %l:%M%P".freeze

format_defaults = {
  default: DATE_FORMAT,
  date_time12: TIME_FORMAT,
  date_time24: "#{DATE_FORMAT} %H:%M",
}.freeze

Date::DATE_FORMATS.merge!(format_defaults)
Time::DATE_FORMATS.merge!(format_defaults)

Weston Ganger
  • 6,324
  • 4
  • 41
  • 39