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

问题描述 投票:0回答:6

我的目标是找到该月指定周中特定日期的日期。举例来说,我想知道 5 月 2 日星期五的日期。 我可以通过时间和日期类获得以下内容。

当年的周数(以星期日为第一)

    Time.strftime(%U)

星期几 (0..7)

    Time.strftime(%w)

但是我如何获得该月的第几周(第一、第二、第三、第四或第五)?

提前致谢!

ruby-on-rails ruby
6个回答
3
投票

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

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

我建议不要这样做,因为它可能会与其他库发生冲突,或者违反了从事该项目的其他开发人员的最低预期。


3
投票

你可以试试这个:

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

1
投票

每月宝石可以做到这一点。首先将 gem 添加到您的 Gemfile 中:

gem 'week_of_month'

然后像这样使用它:

Time.now.week_of_month

如果您需要一周从星期一而不是星期日开始。 将其放入初始值设定项中:

WeekOfMonth.configuration.monday_active = true

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


0
投票

我认为无依赖版本是:

def week_of_month date
  first_of_month = Date.new(date.year, date.month, 1)
  partial_first_week = date.cwday >= first_of_month.cwday ? 1 : 0
  (date.cweek - first_of_month.cweek) + partial_first_week
end

-1
投票

Rails 中有一个很酷的计算方法:

dt.cweek - dt.beginning_of_month.cweek + 1
© www.soinside.com 2019 - 2024. All rights reserved.