Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the first Thursday of the month in Ruby/Rails?

The following Ruby code gets me the first day of each month :

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

Which gives :

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

But how do I get the first Thursday of each month? i.e.

=> Thu, 07 Aug 2014
=> Thu, 04 Sep 2014
=> Thu, 02 Oct 2014
=> Thu, 06 Nov 2014
=> Thu, 04 Dec 2014
like image 933
dwkns Avatar asked Dec 02 '22 19:12

dwkns


1 Answers

There's no need for iterations or conditions just get the so called delta of days till next thursday:

#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
like image 146
AndreDurao Avatar answered Jan 12 '23 01:01

AndreDurao