在 Ruby 或 Rails 中,将东部时间转换为 UTC 的最佳方法是什么?

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

我指的不是

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

Time.now.utc

我得到的是东部时间的文本日期。

我可以将该文本日期转换为 DateTime。我们称它为 eastern_date_time.

现在,我们有一个包含 DateTime 的变量,但除了我们之外没有人知道它是东方。自己转换它会非常繁重。如果日期采用夏令时 (DST)(今年 3 月 8 日至 11 月 1 日),我们必须在 eastern_date_time var 中增加 4 小时才能获得 UTC,如果日期采用标准时间 (ST ) 我们必须向 eastern_date_time 变量添加 5 小时。

我们如何指定我们拥有的是东部日期时间,然后将其转换为 UTC...确定日期是否在 DST/ST 中的东西,并应用 4 或 5 小时正确吗?

我想将我得到的任何类型的日期转换为 UTC,以便存储在我的数据库中。

编辑:

使用“in_time_zone”,我无法将我的东部文本时间转换为 UTC。我怎样才能实现 objective?例如...

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 

这不是我们想要的。我们必须指定 myEasterDateTime 实际上是东部时间...这样当我们在 16:30:00 上执行 myEasterDateTime.utc 时,我们最终会得到 20:30:00.

我怎样才能做到这一点?

有一个 time_in_zone method in the DateTime class:

now.time_in_zone('UTC')

此后 renamed to in_time_zone:

DateTime.now.in_time_zone('US/Pacific')
 => Wed, 22 Apr 2015 12:36:33 PDT -07:00 

Time class 的对象有一个名为 dst? 的方法,它基本上告诉您 DST 是否适用。所以你基本上可以确定 DST/ST 是否适用并决定添加哪个 - 4 或 5.

例如Time.now.dst? 如果 returns 为真,则加 4,否则加 5。

在编辑后的 ​​post 中,您的时间字符串需要与 UTC 的偏移量。

编辑 III: 根据评论(仅设置一个字符串来表示东部时间并需要考虑 DST 等)

text_time = "Nov 27, 2015 4:30 PM"
the_offset = Time.zone_offset('EST') / (60*60)
eastern_time = DateTime.parse(text_time).change(offset: the_offset.to_s) # Fri, 27 Nov 2015 16:30:00 -0500
eastern_time.utc # Fri, 27 Nov 2015 21:30:00 +0000

我是在时区建议的帮助下得到的。

time_text_1 = "Apr 20, 2015 4:30PM" #Scraped as an Eastern Time, with no offset of -5:00 from UTC included
time_text_2 = "Nov 20, 2015 4:30PM" #Scraped as an Eastern Time, with no offset of -5:00 from UTC included

Time.zone = 'Eastern Time (US & Canada)'
my_time_1 = Time.zone.parse time_text_1 # Output: Mon, 20 Apr 2015 16:30:00 EDT -04:00 
my_time_2 = Time.zone.parse time_text_2 # Output: Fri, 20 Nov 2015 16:30:00 EST -05:00 

my_time_1.utc # Output: 2015-04-20 20:30:00 UTC 
my_time_2.utc # Output: 2015-11-20 21:30:00 UTC