2

In rails console if I run the following commands I get:

>> Time.zone.name
=> "UTC"
>> Time.now.getlocal
=> 2015-08-06 16:34:57 -0400

I'm in NYC and the utc offset is -4 hours so the getlocal seems to get the system time zone rather than the environment time zone. This becomes an issue when using the String to_time method:

>> s = "2015-08-06 16:34:57"
=> "2015-08-06 16:34:57"
>> s.to_time(:utc)
=> 2015-08-06 16:34:57 UTC
>> s.to_time(:local)
=> 2015-08-06 16:34:57 -0400
>> s.to_time
=> 2015-08-06 16:34:57 -0400

Any ideas why? Can I force it to look at the environment time zone rather than the system time zone?

My main motivation is that my tests are run locally (so system time is in NYC), but my app is hosted on heroku which has UTC server time, so this caused an issue where a bug slipped through my tests and into production =/

pthamm
  • 1,841
  • 1
  • 14
  • 17
  • possible duplicate of [Why doesn't \`config.time\_zone\` seem to do anything?](http://stackoverflow.com/questions/5073917/why-doesnt-config-time-zone-seem-to-do-anything) – Antarr Byrd Aug 06 '15 at 20:21
  • I believe that's expected behavior. – Chase Aug 06 '15 at 20:21
  • Add an edit about my motivation. Basically I want to have my test environment mimic my production environment, but having different local times creates annoying corner cases where bugs can slip through. – pthamm Aug 06 '15 at 21:07

1 Answers1

0

You can do the following:

"2015-08-06 16:23:25".to_time.in_time_zone

The default behavior of to_time is to use :local according to the API doc (either :local or :utc are valid). For whatever reason, using in_time_zone appears to respect your configured timezone.

To expand on your above posted examples (from my machine):

»  Time.zone.name
=> "UTC"

»  Time.now
=> "2015-08-06T13:49:05.195-07:00"

»  Time.zone.now
=> Thu, 06 Aug 2015 20:49:17 UTC +00:00

»  time_string = "2015-08-06 16:34:57"
=> "2015-08-06 16:34:57"
»  time_string.to_time
=> "2015-08-06T16:34:57.000-07:00"
»  time_string.to_time.in_time_zone
=> Thu, 06 Aug 2015 23:34:57 UTC +00:00

EDIT: Based on the comment below, you can also do the following to not have any time shift added:

»  DateTime.parse(time_string)
=> Thu, 06 Aug 2015 16:34:57 +0000

This will use the configured timezone (UTC in my case)

Ian Selby
  • 3,241
  • 1
  • 25
  • 18
  • if you notice the last two outputs change the hour by 7, which unfortunately breaks the logic of what I'm trying to build :( – pthamm Aug 06 '15 at 21:05