How do I move (not convert) a time into a new time zone?
I have a DateTime d
and a string tz
that is a valid ActiveSupport::TimeZone key (e.g. "UTC", "Eastern Time (US & Canada)", "America/Chicago", etc.). How do I get a new DateTime d2 such that everything is the same, but the offset of d2
now reflects that of the time zone corresponding to tz
?
Note that I do not want to convert the time into the new time zone. I want a new DateTime with everything else equal, but with the offset different.
For example, if I have d = <today @ 5:00 PM UTC>
, a开发者_开发百科nd tz = 'Central Time (US & Canada)'
, what I want is d2 = <today @ 5:00 PM -0600>
, not d2 = <today @ 11:00 AM -0600>
.
Given tz
, you can convert that to an offset as a fraction of a day:
offset = ActiveSupport::TimeZone.new(tz).utc_offset / 60 / 60 / 24.0
=> -0.25 # for 'Central Time (US & Canada)'
You can then pass this into DateTime.civil
along with existing details from d
to create the new object:
d2 = DateTime.civil(d.year, d.month, d.day, d.hour, d.min, d.sec, offset)
精彩评论