红宝石确定季节(秋季,冬季,春季或夏季)

时间:2013-03-14 16:26:47

标签: ruby datetime

我正在编写一个应该确定"赛季"年度基于日期范围:

例如:

January 1 - April 1: Winter
April 2 - June 30: Spring
July 1 - September 31: Summer
October 1 - December 31: Fall

我不确定这样做的最佳方式(或最好的红宝石方式)。其他人遇到过如何做到这一点?

4 个答案:

答案 0 :(得分:6)

9月31日?

正如leifg建议的那样,这里是代码:

require 'Date'

class Date

  def season
    # Not sure if there's a neater expression. yday is out due to leap years
    day_hash = month * 100 + mday
    case day_hash
      when 101..401 then :winter
      when 402..630 then :spring
      when 701..930 then :summer
      when 1001..1231 then :fall
    end
  end
end

一旦定义,请将其称为像这样:

d = Date.today
d.season

答案 1 :(得分:2)

您可以尝试使用范围和日期对象:

http://www.tutorialspoint.com/ruby/ruby_ranges.htm

答案 2 :(得分:1)

没有范围。

  require 'date'

    def season
      year_day = Date.today.yday().to_i
      year = Date.today.year.to_i
      is_leap_year = year % 4 == 0 && year % 100 != 0 || year % 400 == 0
      if is_leap_year and year_day > 60
        # if is leap year and date > 28 february 
        year_day = year_day - 1
      end

      if year_day >= 355 or year_day < 81
        result = :winter
      elsif year_day >= 81 and year_day < 173
        result = :spring
      elsif year_day >= 173 and year_day < 266
        result = :summer
      elsif year_day >= 266 and year_day < 355
       result = :autumn
      end

      return result
    end

答案 3 :(得分:0)

Neil Slater's answer's的方法很棒,但对我而言,这些日期并不完全正确。它们显示秋天结束于12月31日,在我能想到的任何情况下都是如此。

使用northern meteorological个季节:

  
      
  • 春季从3月1日至5月31日;
  •   
  • 夏季从6月1日至8月31日;
  •   
  • 秋季(秋季)从9月1日至11月30日;和
  •   
  • 冬季从12月1日到2月28日(a年的2月29日)。
  •   

该代码需要更新为:

require "date"

class Date
  def season
    day_hash = month * 100 + mday
    case day_hash
      when 101..300 then :winter
      when 301..531 then :spring
      when 601..831 then :summer
      when 901..1130 then :fall
      when 1201..1231 then :winter
    end
  end
end
相关问题