Berimbolo
Berimbolo

Reputation: 313

How to get all 'specific days' within a date range

How can I get let's say All the dates for Saturday and Sunday from X year to Y year and store them as array? Pseudo code would be

(year_today..next_year).get_all_dates_for_saturday_and_sunday

Or perhaps there are gems that cater to this already?

Upvotes: 0

Views: 805

Answers (3)

dp7
dp7

Reputation: 6749

Try this:

(Date.today..Date.today.next_year).select { |date|
  date.sunday? or date.saturday?
}

#=> [Sat, 03 Sep 2016,Sun, 04 Sep 2016,Sat, 10 Sep 2016,Sun, 11 Sep 2016...

Upvotes: 3

Cary Swoveland
Cary Swoveland

Reputation: 110675

The following approach emphasizes efficiency over brevity, by avoiding the need to determine if every day in a range is a given day (or one of two given days) of the week.

Code

require 'date'

def dates_by_years_and_wday(start_year, end_year, wday)
  (first_date_by_year_and_wday(start_year, wday)...
   first_date_by_year_and_wday(end_year+1, wday)).step(7).to_a
end

def first_date_by_year_and_wday(year, wday)
   d = Date.new(year)
   d + (wday >= d.wday ? wday - d.wday : 7 + wday - d.wday)
end

Notice that the range is defined with three dots, meaning the first date in end_year is excluded.

Example

SATURDAY = 6
SUNDAY = 0
start_year, end_year = 2015, 2017

dates_by_years_and_wday(start_year, end_year, SATURDAY)
  #=> [#<Date: 2015-01-03 ((2457026j,0s,0n),+0s,2299161j)>,
  #    #<Date: 2015-01-10 ((2457033j,0s,0n),+0s,2299161j)>,
  #    ...   
  #    #<Date: 2017-12-30 ((2458118j,0s,0n),+0s,2299161j)>]
dates_by_years_and_wday(start_year, end_year, SATURDAY).size
  #=> 157

dates_by_years_and_wday(start_year, end_year, SUNDAY)
  #=> [#<Date: 2015-01-04 ((2457027j,0s,0n),+0s,2299161j)>,
  #    #<Date: 2015-01-11 ((2457034j,0s,0n),+0s,2299161j)>,
  #    ...   
  #    #<Date: 2017-12-31 ((2458119j,0s,0n),+0s,2299161j)>]    
dates_by_years_and_wday(start_year, end_year, SUNDAY).size
  #=> 157

Upvotes: 0

siegy22
siegy22

Reputation: 4413

(Date.today..(Date.today + 1.year)).select do |date| 
  date.saturday? || date.sunday? 
end # => [Sat, 03 Sep 2016, Sun, 04 Sep 2016, Sat, 10 Sep 2016, ...

This will then give you an array of 104 elements containing every date which is a saturday or a sunday between today and today in a year.

Upvotes: 0

Related Questions