Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Time in UTC to Pacific time

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.

like image 408
Mo. Avatar asked Jul 09 '10 15:07

Mo.


People also ask

What is UTC time converted to PST?

Coordinated Universal Time is 8 hours ahead of Pacific Standard Time.

Is UTC always 8 hours ahead of PST?

Currently has same time zone offset as PST (UTC -8) but different time zone name. Pacific Standard Time (PST) is 8 hours behind Coordinated Universal Time (UTC).

Is UTC 7 hours ahead of PST?

UTC is 8 hours ahead of Pacific Standard Time (e.g., 0000 UTC is 1600 PST the previous day, while 1200 UTC is 0400 PST the same day), and 7 hours ahead of Pacific Daylight Time (e.g., 0000 UTC is 1700 PDT the previous day, while 1200 UTC is 0500 PDT the same day).

How do I convert UTC time to my time?

(GMT-5:00) Eastern Time (US & Canada)Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.


2 Answers

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)")
like image 120
Geoff Lanotte Avatar answered Sep 18 '22 14:09

Geoff Lanotte


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.

like image 21
michaelmichael Avatar answered Sep 18 '22 14:09

michaelmichael