获取每个月的最后一个星期五的那一天

时间:2013-03-04 18:52:44

标签: ruby-on-rails ruby

我是红宝石的新手,我希望得到每月最后一个星期五的那一天。 例如,3月的最后一个星期五是29,即4月26日的最后一个星期五。 那么,我该如何获得解决方案呢? 我正在使用rails框架。

方法.cweek返回一年中的一周,但不返回当月的一周。

4 个答案:

答案 0 :(得分:9)

#!/usr/bin/env ruby

require 'date'

(1..12).each do |month|
  d = Date.new(2013, month, -1)
  d -= (d.wday - 5) % 7
  puts d
end

Source(第二/第三次Google结果..)

答案 1 :(得分:4)

我会选择李的回答,我只发布这个,因为(我认为)这很酷。

使用gem Chronichttps://github.com/mojombo/chronic):

#Last Friday of this coming December
require 'chronic'
last_friday = Chronic.parse("First Friday of next January") - 1.week

答案 2 :(得分:2)

可以在一行中检索一个月的最后一个星期五:

def last_fridays_for_every_month_of_year(year)
  (1..12).map do |month|
    Date.new(year, month, -1).downto(0).find(&:friday?)
  end
end

你可以这样使用它:

last_fridays_for_every_month_of_year 2013
#=> [#<Date: 2013-01-25 ((2456318j,0s,0n),+0s,2299161j)>,
     #<Date: 2013-02-22 ((2456346j,0s,0n),+0s,2299161j)>,
     #<Date: 2013-03-29 ((2456381j,0s,0n),+0s,2299161j)>,
     #<Date: 2013-04-26 ((2456409j,0s,0n),+0s,2299161j)>,
     #<Date: 2013-05-31 ((2456444j,0s,0n),+0s,2299161j)>,
     #<Date: 2013-06-28 ((2456472j,0s,0n),+0s,2299161j)>,
     #<Date: 2013-07-26 ((2456500j,0s,0n),+0s,2299161j)>,
     #<Date: 2013-08-30 ((2456535j,0s,0n),+0s,2299161j)>,
     #<Date: 2013-09-27 ((2456563j,0s,0n),+0s,2299161j)>,
     #<Date: 2013-10-25 ((2456591j,0s,0n),+0s,2299161j)>,
     #<Date: 2013-11-29 ((2456626j,0s,0n),+0s,2299161j)>,
     #<Date: 2013-12-27 ((2456654j,0s,0n),+0s,2299161j)>]

答案 3 :(得分:1)

require "active_support/core_ext"

end_of_month = Date.today.end_of_month
if end_of_month - end_of_month.beginning_of_week >= 4
   end_of_month+5.days
else
   end_of_month-2.days
end
# => Fri, 29 Mar 2013