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

后端 未结 3 1916
无人及你
无人及你 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:43

    fun one! :D

     start_date = Date.today # your start
     end_date = Date.today + 1.year # your end
     my_days = [1,2,3] # day of the week in 0-6. Sunday is day-of-week 0; Saturday is day-of-week 6.
     result = (start_date..end_date).to_a.select {|k| my_days.include?(k.wday)}
    

    using the data above you'll get an array of all Mon/Tue/Weds between now and next year.

提交回复
热议问题