Converting Time in UTC to Pacific time

2019-03-24 15:32发布

I get a string from a external method with a time and date like so "07/09/10 14:50" is there any way I can convert that time in ruby to 'Pacific US' time knowing its 'UTC' time? with changes accounted for in the date? I.e if the time difference results in the day being different.

3条回答
对你真心纯属浪费
2楼-- · 2019-03-24 15:58

Since it appears you are using rails, you have quite a few options. I suggest reading this article that talks all about time zones.

To convert to PST, both of these are rails-specific methods. No need to re-invent the wheel:

time = Time.parse("07/09/10 14:50")
time.in_time_zone("Pacific Time (US & Canada)")

Hope this helps

UPDATE: rails might try to get smart and give the time you specify as a string a time zone. To ensure that the time parses as UTC, you should specify in the string:

time = Time.parse("07/09/10 14:50 UTC")
time.in_time_zone("Pacific Time (US & Canada)")
查看更多
Root(大扎)
3楼-- · 2019-03-24 16:09

require 'time'

If you want pacific time just subtract 25200 seconds from Time.new There is a 7 hour difference between pacific time and GMT.

t = Time.parse((Time.new-25200).to_s)

Then use strftime to format however you want it to look.

puts t.strftime("%A %D at %I:%M%p")

查看更多
三岁会撩人
4楼-- · 2019-03-24 16:19

To convert from string form to a date or time object you need to use strptime

require 'date'
require 'time'

my_time_string = "07/09/10 14:50"
to_datetime = DateTime.strptime(my_time_string, "%m/%d/%y %H:%M")    

utc_time = Time.parse(to_datetime.to_s).utc
pacific_time = utc_time + Time.zone_offset("PDT")

puts utc_time
puts pacific_time

This is pure ruby, so there are likely some rails-specific methods you could use specifically for this task, but this should get you started.

查看更多
登录 后发表回答