如何在Ruby / Rails中获得本月的第一个星期四?

时间:2014-07-01 11:09:34

标签: ruby-on-rails ruby

以下Ruby代码让我每个月的第一天:

require 'active_support/all'

# get the date at the beginning of this month
date = Date.today.beginning_of_month

# get the first day of the next 5 months
5.times do |num|
  date = date.next_month
  p date
end

给出了:

=> Fri, 01 Aug 2014
=> Mon, 01 Sep 2014
=> Wed, 01 Oct 2014
=> Sat, 01 Nov 2014
=> Mon, 01 Dec 2014

但是我如何获得每个月的第一个星期四?即。

=> Thu, 07 Aug 2014
=> Thu, 04 Sep 2014
=> Thu, 02 Oct 2014
=> Thu, 06 Nov 2014
=> Thu, 04 Dec 2014

6 个答案:

答案 0 :(得分:3)

只是为了好玩

class Date
  def skip_to_thursday
    # given current weekday, how many days we need to add for it to become thursday
    # for example, for monday (weekday 1) it's 3 days

    offset = lambda {|x| (4-x) % 7 }    
    self + offset[wday]
  end
end


# get the date at the beginning of this month
date = Date.today.beginning_of_month

date.skip_to_thursday # => Thu, 03 Jul 2014

答案 1 :(得分:3)

我的意见:

date_begin = Date.today.beginning_of_month
date_end = date_begin + 5.month
[*date_begin..date_end].select(&:thursday?).uniq(&:month)
=> [Thu, 03 Jul 2014, Thu, 07 Aug 2014, Thu, 04 Sep 2014, Thu, 02 Oct 2014, Thu, 06 Nov 2014]

答案 2 :(得分:2)

这是我的方式:

def first_thursday
  date = Date.today.beginning_of_month
  date += 1 until date.wday == 4
  date
end

first_thursday # => Thu, 03 Jul 2014 

答案 3 :(得分:2)

没有必要进行迭代或条件才能获得所谓的天数增量到下周四:

#4 is thursday because wday starts at 0 (sunday)

date = Date.today.beginning_of_month
date += (4 - date.wday) % 7
p date
=> Thu, 03 Jul 2014

答案 4 :(得分:1)

你可以使用这样的东西:

def first_thursday(months_ahead)
  start_of_month = months_ahead.months.from_now.beginning_of_month.to_date
  start_of_month += (4 - start_of_month.cwday) % 7
end

first_thursday 1
=> Thu, 07 Aug 2014
first_thursday 2
=> Thu, 04 Sep 2014

答案 5 :(得分:0)

我遇到了我需要构建的recurring_events功能的问题。我更改了一些变量以查找第一个星期四,但是它也显示了如何计算答案(如果有星期几和星期几的话)以找到第二个或第三个星期四(或该日的星期几) 。

def find_thursday
  start_of_month = DateTime.now.beginning_of_month
  month_day = nil
  loop do
    month_day = start_of_month += 1.day
    break if month_day.wday == find_weekday("Thu")
  end
  return month_day
end


def find_weekday
  d = default_weekdays.find { |d| d[:day] == start_date.strftime("%a") }
  d[:count]
end


def default_weekdays
  return [
    { day: 'Sun', count: 0 },
    { day: 'Mon', count: 1 },
    { day: 'Tue', count: 2 },
    { day: 'Wed', count: 3 },
    { day: 'Thu', count: 4 },
    { day: 'Fri', count: 5 },
    { day: 'Sat', count: 6 },
  ]
end
相关问题