Ruby – 获得下一个夏令时的变化
我知道有一种方法可以确定某一时间是否在夏令时( Time.now.dst?
)上,但是有一种方法可以为我们提供夏令时改变时的下一个日期吗?
例如,Google 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 => #,#>, #, #>> 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刚从操作系统中获取布尔值吗?
这个Time类的扩展怎么样:
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
。 您可以仅在自己的时区应用此function,但它可以解决您的问题。