LewlSauce
LewlSauce

Reputation: 5872

Convert time to time zone without changing the actual time

I have a Time object that I'm trying to change the time zone for, but I don't want to change the actual value. For example, when I convert 11:00:00 UTC to MDT, it becomes 5:00 MDT:

[6] pry(#<ScheduledDate>)> Time.parse("#{start_date} #{first_allowed_time}")
=> 2020-09-05 11:00:00 +0000
[7] pry(#<ScheduledDate>)> Time.parse("#{start_date} #{first_allowed_time}").in_time_zone("Mountain Time (US & Canada)")
=> Sat, 05 Sep 2020 05:00:00 MDT -06:00
[8] pry(#<ScheduledDate>)> 

How can I simply add a time zone to the UTC time without actually changing its time?

Upvotes: 1

Views: 663

Answers (1)

Alex P
Alex P

Reputation: 6072

The Time object always stores times in UTC. It's generally best to store and manipulate times in UTC, and handle the timezone separately when displaying the time. So your Time object will always be in UTC, though you can display it in different zones. This uses Rails' TimeWithZone class, but you shouldn't instantiate those directly. Using them through helpers like in_time_zone is better.

If you need to store a time zone, storing the time zone name is a good solution. These are defined by IANA and supported by Rails.

Upvotes: 2

Related Questions