1

I have a problem with my time_zone in Rails APP.

I have it configured to London in my application.rb:

config.time_zone = 'London'
config.active_record.default_timezone = :local

Then, in my controller I have something like this:

Element.create(start_hour: Time.strptime('16/04/2018 12:00', '%d/%m/%Y %H:%M'))

What can I do to save this date and when I print the time in the view it returns me the London time?

For example, in the previous example, now in my view: element.start_hour.strftime('%H:%M') prints 13:00 but I want that it prints 12:00

fcastillo
  • 938
  • 1
  • 11
  • 24
  • Have you set ActiveRecord's time zone as well? This might help you: https://stackoverflow.com/questions/6118779/how-to-change-default-timezone-for-active-record-in-rails – Gerry Apr 02 '18 at 16:33
  • @Gerry, Yes, I have `config.active_record.default_timezone = :local` in my `application.rb` too. – fcastillo Apr 02 '18 at 16:38
  • Have you restart your rails application after changing the application.rb? – Salil Apr 02 '18 at 17:09
  • @Salil, No because I haven't changed the `application.rb` – fcastillo Apr 02 '18 at 17:20
  • What is the o/p of `Time.strptime('16/04/2018 12:00', '%d/%m/%Y %H:%M')` & `Time.strptime('16/04/2018 12:00', '%d/%m/%Y %H:%M').zone` – Salil Apr 02 '18 at 17:51
  • Also, `config.time_zone` does not change the `:local` timezone. That will be based on system time. Be sure ``date`` returns London time. [update: date the unix command, not ruby] – Jacob Vanus Apr 02 '18 at 18:22
  • @Salil, `'2018-04-16 12:00:00 +0200'` & `'CEST'` – fcastillo Apr 03 '18 at 08:47
  • @JacobVanus, my date unix command (I'm in local) returns spanish date but in production returns UTC+0 and the result in views is the same. – fcastillo Apr 03 '18 at 08:51
  • 1
    Now it works! I added `zone` method to `Time` before save the field. `Element.create(start_hour: Time.zone.strptime('16/04/2018 12:00', '%d/%m/%Y %H:%M'))` then the time to save is transformed to `11:00` before save. – fcastillo Apr 03 '18 at 10:20
  • I'd recommend following Thoughtbot's recommendations for more control over how time zones get saved and display. If you keep the default at UTC, you can do more with controllers/views to reliably ensure you're getting the right output. https://robots.thoughtbot.com/its-about-time-zones – Matt Apr 03 '18 at 14:44

0 Answers0