How to set UTC format for API serializer response in Rails?

Viewed 154

We have configured application time in london zone

config.time_zone = 'London'

but need to return the date time in UTC format for API response's to avoid day light saving issue's

I tried changing the time zone for API controller's alone - added a before action to set UTC time for API response

 api_controller.rb

 before_action :set_utc_time

 def set_utc_time
  Time.zone = 'UTC'
 end

But, it seems it is also reflected in web application's response too and london time zone is changed to UTC for the entire application

response_formatter.rb

Time.use_zone('UTC') do
render json: response_data, status: :ok
end

so tried to execute the time zone for serializer response formatter by setting time zone within a block , but that doesn't seem to work

Note: we are using fast_json_api serializer

sample serialiser:

class LinguistUnavailabilitySerializer
  include FastJsonapi::ObjectSerializer
  attributes :id, :linguist_id, :departure_time, :return_time, :reason
end

I need to set utc time zone format for API Response alone but it should not be reflect in the application time zone

Any ideas ?

1 Answers

could you try to redefine the attributes for your time attr https://github.com/Netflix/fast_jsonapi#attributes and use the method zone_offset and do the addition between the local time and the new time zone for example

sample serialiser:

class LinguistUnavailabilitySerializer
  include FastJsonapi::ObjectSerializer
  attributes :id, :linguist_id, :departure_time, :return_time, :reason

  attribute :departure_time do |object|
    a = %w(%Y %m %d %H %M %S)
    # ["%Y", "%m", "%d", "%H", "%M", "%S"]
    tm = departure_time
    # 2014-11-03 17:46:02 +0530
    a.map { |s| tm.strftime(s) }
    # ["2014", "11", "03", "17", "46", "02"]
    a.map! { |s| tm.strftime(s).to_i }
    # [2014, 11, 3, 17, 46, 2]
    Time.new(*a, Time.zone_offset('PST'))
  end
end

conversion time based on https://stackoverflow.com/a/26714154/10124678

Related