I am new with ruby and I want to get the day of the last Friday of each month. For example, the last Friday of March is 29, the Last Friday of April 26. So, how can I get a solution? I'm using the rails framework.
The method .cweek
returns the week of the year, but does not return the week of the current month.
You could combine these two formulas into a single formula of =WORKDAY. INTL(EOMONTH(A2,-1),1,“0111111”). You can also combine EOMONTH and WORKDAY. INTL to find the last Friday of a month.
datetime. date(2024,2,1)+relativedelta(day=31, weekday=FR(-1), weeks=4) gives 22 March 2024 but the last Friday of that month is 29 March. But datetime. date(2024,2,1)+relativedelta(day=31, weekday=FR(-1), months=1) gives you the correct answer.
=EOMONTH(A2, -1) - returns the last day of the month, one month before the date in cell A2. Instead of a cell reference, you can hardcode a date in your EOMONTH formula.
EOMONTH returns the last day of a month from a date. Here, we use the EOMONTH function to go to the last day of the previous month. Then, we add 1 to get the first day of the current month. To perform the previous example with the EOMONTH function, we need to use the formula =EOMONTH(A2,-1)+1 in cell B2.
#!/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 (second/third Google result..)
I would go with Lee's answer, I'm only posting this one because (I thought) it's pretty cool.
Using gem Chronic
(https://github.com/mojombo/chronic):
#Last Friday of this coming December
require 'chronic'
last_friday = Chronic.parse("First Friday of next January") - 1.week
Retrieving the last friday of a month can be made in a single line:
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
You may use it like this:
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)>]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With