How do I get all Sundays between two dates in Ruby?

后端 未结 3 1902
无人及你
无人及你 2020-12-31 01:20

I\'m working on a form where the user enters a date range and selects from a list of checkboxes a day/days of the week i.e Sunday, Monday, Tuesday, Wednesday, Thursday, Frid

3条回答
  •  一向
    一向 (楼主)
    2020-12-31 01:28

    Another approach is to group your date range by wday and pick off your day of the week:

    datesByWeekday = (start_date..end_date).group_by(&:wday)
    datesByWeekday[0] # All Sundays
    

    for example, to get all Saturdays in March 2019:

    > (Date.new(2019,03,01)..Date.new(2019,04,01)).group_by(&:wday)[0]
    => [Sun, 03 Mar 2019, Sun, 10 Mar 2019, Sun, 17 Mar 2019, Sun, 24 Mar 2019, Sun, 31 Mar 2019]
    

    https://apidock.com/ruby/Date/wday

提交回复
热议问题