0

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)
John
  • 1,273
  • 3
  • 27
  • 61
  • Possible duplicate of http://stackoverflow.com/questions/13075617/rails-3-2-8-how-do-i-get-the-week-number-from-rails. Did you review this answer and have subsequent questions? Can you show us your code? – steve klein Jun 16 '15 at 13:03
  • @steveklein I think he means the second week in June as the week number, not the week number of the year. – j-dexx Jun 16 '15 at 13:09
  • in this url it is taking week number in a entire year like 44, but in my case weak number should be less than or equal to 5. as this week number belongs to a month. i want to have a method which takes the above three parameters and gives the weak dates in an array format like [1,2,3,4] – John Jun 16 '15 at 13:15

1 Answers1

2

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]
j-dexx
  • 10,286
  • 3
  • 23
  • 36