How to parse a time string to a specific time zone?

I have this line:

Sunday, October 7, 4:00 p.m.

When I use Time.parse , Ruby assumes that the time zone is UTC. How can I tell Ruby to give me a time zone of -0700? I tried using

 tz.utc_to_local(Time.parse(string)) 

but I still get UTC time zone +0000.

+4
source share
2 answers

Make sure the time zone is set correctly.

 config.time_zone = 'Eastern Time (US & Canada)' 

Time.parse should use the current time zone by default, but you can also try

 Time.parse('####').in_time_zone 
0
source

β€œWhen analyzing time information, it’s important to never do this without specifying the time zone.

This gem of advice from this useful blogpost: Working with time zones in Ruby on Rails .

Regardless of whether you use rails or not, the time bar is always bound to the time zone. In your case, you assume that the time line has an offset of -0700, but does not pass the time zone information to the analysis method (which assumes it's UTC).

 > Rails.application.config.time_zone => "Mountain Time (US & Canada)" 

This is because I have the following configuration:

 config.time_zone = 'Mountain Time (US & Canada)' > string = "Sunday, Oct 7 4:00pm" => "Sunday, Oct 7 4:00pm" > Time.parse(string) => 2012-10-07 16:00:00 -0600 > Time.parse(string).zone => "MDT" 

It works in a similar way in a pure ruby:

 > require 'time' => true > Time.local( 2012, 10, 07 ) => 2012-10-07 00:00:00 -0600 > Time.local( 2012, 10, 07 ).zone => "MDT" > string = "Sunday, Oct 7 4:00pm" => "Sunday, Oct 7 4:00pm" > Time.parse(string) => 2012-10-07 16:00:00 -0600 > Time.parse(string).zone => "MDT" 
0
source

Source: https://habr.com/ru/post/1438308/


All Articles