Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby or Rails, what is the best way to convert Eastern Time to UTC?

I'm not referring to

myDateTime = DateTime.now
myDateTime.new_offset(Rational(0, 24))

or

Time.now.utc

What I have is a text date is given in Eastern Time.

I can convert that text date into a DateTime. Let's call it eastern_date_time.

Now, we have a variable containing an DateTime, but nothing knows it's eastern besides us. Converting it ourselves would be quite onerous. If the date in Daylight Savings Time (DST) (March 8 to November 1st this year), we'd have to add 4 hours to our eastern_date_time var to get UTC, and if the date is in Standard Time (ST) we'd have to add 5 hours to our eastern_date_time variable.

How can we specify that what we have is an Eastern DateTime, and then convert it to UTC... something that will determine if the date is in the DST/ST, and apply the 4 or 5 hours properly?

I want to convert any sort of date I get into UTC, for storage in my database.

EDIT:

Using `in_time_zone', I'm unable to convert my Eastern Text Time to UTC. How can I achieve that objective? For example...

text_time = "Nov 27, 2015 4:30 PM" #given as Eastern
myEasternDateTime = DateTime.parse text_time # => Fri, 27 Nov 2015 16:30:00 +0000 
#now we need to specify that this myEasternDateTime is in fact eastern. However, it's our default UTC. If we use in_time_zone, it just converts the date at UTC to Eastern
myEasternDateTime.in_time_zone('Eastern Time (US & Canada)') # => Fri, 27 Nov 2015 11:30:00 EST -05:00 
myEasternDateTime.utc # => Fri, 27 Nov 2015 16:30:00 +0000 

That's not what we want. We have to specify that myEasterDateTime is in fact eastern... so that when we do a myEasterDateTime.utc on 16:30:00 we end up getting 20:30:00.

How can I accomplish this?

like image 359
chris P Avatar asked Apr 22 '15 19:04

chris P


2 Answers

There was a time_in_zone method in the DateTime class:

now.time_in_zone('UTC')

It has since been renamed to in_time_zone:

DateTime.now.in_time_zone('US/Pacific')
 => Wed, 22 Apr 2015 12:36:33 PDT -07:00 
like image 196
hd1 Avatar answered Sep 24 '22 20:09

hd1


The objects of Time class have a method called dst? which basically tells you whether or not DST is applicable or not. So you can basically identify whether DST/ST is applicable and decide which to add - 4 or 5.

e.g. Time.now.dst? If it returns true, add 4, otherwise add 5.

like image 36
Jerry Avatar answered Sep 24 '22 20:09

Jerry