【问题标题】:How can I convert a Time from some timezone to UTC, taking into account Daylight Saving, in Ruby?考虑到夏令时,如何在 Ruby 中将时间从某个时区转换为 UTC?
【发布时间】:2013-05-24 16:08:38
【问题描述】:

我有一个应用程序,其中不同的用户位于全球不同的地方(我知道他们的时区),他们可以输入日期和时间,我需要将所有内容以 UTC 格式存储在数据库中。

通常要实例化我的时间变量,我正在做:

DateTime.new(date.year, date.month, date.day, hours, minutes, 0)

这已经是 UTC,但没有转换。

如果我使用 time_zone(即“Melbourne”)向该字符串添加第 7 个参数,那么它会将其解释为澳大利亚的日期,并且当转换为 UTC 时,生成的 DateTime 会落后 10 小时,并且有效。

但是,这没有考虑夏令时。

我需要做到这一点(例如来自日期/时间组件的 DateTime),这样(例如,在澳大利亚的情况下),在 4 月 9 日使用相同的小时/分钟会给我转换为 UTC 时的偏移量与我使用 4 月 5 日时不同。

有什么想法吗?

谢谢!
丹尼尔

【问题讨论】:

标签: ruby-on-rails ruby datetime timezone


【解决方案1】:

看看tzinfo

irb(main):002:0> require 'tzinfo'
=> true
irb(main):003:0> tz = TZInfo::Timezone.get("Australia/Melbourne")
=> #<TZInfo::DataTimezone: Australia/Melbourne>

irb(main):004:0> tz.utc_to_local(Time.parse("2013-04-05 00:00:00"))
=> Fri Apr 05 11:00:00 UTC 2013
irb(main):005:0> tz.utc_to_local(Time.parse("2013-04-09 00:00:00"))
=> Tue Apr 09 10:00:00 UTC 2013

irb(main):015:0> tz.local_to_utc(Time.parse("2013-04-09 00:00:00"))
=> Mon Apr 08 14:00:00 UTC 2013
irb(main):016:0> tz.local_to_utc(Time.parse("2013-04-05 00:00:00"))
=> Thu Apr 04 13:00:00 UTC 2013

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 2012-05-01
    • 2021-01-21
    • 2012-06-24
    相关资源
    最近更新 更多