Ruby - 获取下一个夏令时更改

Ruby - Getting the next Daylight Savings change

我知道有一种方法可以确定某个时间是否在夏令时 (Time.now.dst?),但是有没有一种方法可以告诉我们下一个夏令时将发生变化的日期?

例如,Google returns Sunday, November 1 作为 2015 年的下一个夏令时更改。

由于这些是基于其他值的日期,例如您正在使用的时区,因此它需要像 ActiveSupport/TZInfo 这样的模块。

require 'active_support/core_ext/time/zones'
tz = TZInfo::Timezone.get('US/Pacific')
     # pick a timezone to work with
tz.current_period     #returns an object of the current period 

  => #<TZInfo::TimezonePeriod: #<TZInfo::TimezoneTransitionDefinition: 

     #<TZInfo::TimeOrDateTime: 1425808800>,#<TZInfo::TimezoneOffset: -28800,3600,PDT>>,

     #<TZInfo::TimezoneTransitionDefinition: #<TZInfo::TimeOrDateTime: 1446368400>,

     #<TZInfo::TimezoneOffset: -28800,0,PST>>>

tz.current_period.local_start.to_s
 # => "2015-03-08T03:00:00+00:00"
tz.current_period.local_end.to_s
 #  => "2015-11-01T02:00:00+00:00"

有一件事我还没有弄清楚,因为常规 Ruby Core 会这样做:

Time.now.dst?
   # => true

它是从哪里获得这些信息的?我通过 ActiveSupport 找到了 TZInfo 类。 Ruby 只是从 OS 中得到一个布尔值吗?

这个时间延长怎么样class:

class Time
  class << self
    def next_dst_change
      startdate = Date.today
      enddate = Date.today.end_of_year
      match = Date.today.to_time.dst? ? false : true
      startdate.upto(enddate).find { |date| date.to_time if date.to_time.dst? == match }
   end  
 end  
end

现在您可以做到 Time.next_dst_change。您只能在您自己的时区应用它,但它可以解决您的问题。