如何计算Ruby中当月的当前周数

时间:2015-05-26 21:38:57

标签: ruby-on-rails ruby

我的目标是找到该月某一周特定日期的日期。比如说,我想知道5月2日星期五的日期。 我可以通过时间和日期课程获得以下内容。

当年的周数(将周日视为第一个)

    Time.strftime(%U)

星期几(0..7)

    Time.strftime(%w)

但是我如何得到它所在的那个星期(第1,第2,第3,第4或第5个)?

提前致谢!

4 个答案:

答案 0 :(得分:1)

为了处理您列出的要求,我建议您编写一个帮助函数来获取一个月内的周数。

def get_month_week(date_or_time, start_day = :sunday)

  date = date_or_time.to_date
  week_start_format = start_day == :sunday ? '%U' : '%W'

  month_week_start = Date.new(date.year, date.month, 1)
  month_week_start_num = month_week_start.strftime(week_start_format).to_i
  month_week_start_num += 1 if month_week_start.wday > 4 # Skip first week if doesn't contain a Thursday

  month_week_index = date.strftime(week_start_format).to_i - month_week_start_num
  month_week_index + 1 # Add 1 so that first week is 1 and not 0

end

然后可以这样调用:

get_month_week(Date.today)

如果你真的觉得猴子修补是你想要的,你可以添加到Date类:

class Date

  def month_week(start_day = :sunday)

    week_start_format = start_day == :sunday ? '%U' : '%W'

    month_week_start = Date.new(self.year, self.month, 1)
    month_week_start_num = month_week_start.strftime(week_start_format).to_i
    month_week_start_num += 1 if month_week_start.wday > 4 # Skip first week if doesn't contain a Thursday

    month_week_index = self.strftime(week_start_format).to_i - month_week_start_num
    month_week_index + 1 # Add 1 so that first week is 1 and not 0

  end

end

这可以在如此的日期或时间调用:

Date.today.month_week

Time.current.to_date.month_week

我建议不要这样做,因为它可能会与其他图书馆发生冲突,或者对其他从事该项目的开发人员造成最小的意外。

答案 1 :(得分:0)

week-of-month宝石会这样做。首先将gem添加到Gemfile:

gem 'week_of_month'

然后使用它:

Time.now.week_of_month

如果您需要在星期一而不是星期日开始一周。把它放在初始化器中:

WeekOfMonth.configuration.monday_active = true

答案 2 :(得分:0)

你可以试试这个:

current_time = Time.zone.now
beginning_of_the_month = current_time.beginning_of_month
puts current_time.strftime('%U').to_i - beginning_of_the_month.strftime('%U').to_i + 1

或者

Time.parse('2015-01-08').strftime('%U').to_i - Time.parse('2015-01-01').strftime('%U').to_i + 1

答案 3 :(得分:0)

def number_of_weeks_month(start_of_month, count, end_of_month)
    if start_date > end_of_month
        return count
    else
        number_of_weeks_month(start_date.end_of_week + 1, count + 1, end_of_month)
    end
end

number_of_weeks_month(Date.parse("2017-11-01"),0,Date.parse("2017-11-30")) 对于11月的月份,它给了4个