how to get weak days of a particular week for a selected month and year in rails?

556 views Asked by At

I want to get all the weak days of a particular week, for the selected year and month. I am getting data like year= 2015, month= 6 ,and weeknumber = 2 in controller. how to get week days for this particular data in rails?

i want a method like this which outputs the weekdays by taking week number. but the week number should be for that month like it should be less than or equal to five. below code outputs the week number for the whole year.

require 'date'

def week_dates( week_num )
year = Time.now.year
week_start = Date.commercial( year, week_num, 1 )
week_end = Date.commercial( year, week_num, 7 )
week_start.strftime( "%m/%d/%y" ) + ' - ' +        week_end.strftime("%m/%d/%y" )
end

puts week_dates(22)
1

There are 1 answers

0
j-dexx On

Because you're using rails you have the active support methods for beginning_of_week and end_of_week documented here you can do this

# first week in June
d = Date.new(2015,6, 1)
# => Mon, 01 Jun 2015

# add a week to get the second week
d += 1.week
# => Mon, 08 Jun 2015

(d.beginning_of_week..d.end_of_week).to_a
#=> [Mon, 08 Jun 2015, Tue, 09 Jun 2015, Wed, 10 Jun 2015, Thu, 11 Jun 2015, Fri, 12 Jun 2015, Sat, 13 Jun 2015, Sun, 14 Jun 2015]

If you want your week to start on sunday you can do this, passing the beginning day of the week:

(d.beginning_of_week(:sunday)..d.end_of_week(:sunday)).to_a
#=> [Sun, 31 May 2015, Mon, 01 Jun 2015, Tue, 02 Jun 2015, Wed, 03 Jun 2015, Thu, 04 Jun 2015, Fri, 05 Jun 2015, Sat, 06 Jun 2015]