Date search for a given week number

I am trying to do the math by date based on the week number of a given year. For example:

date = Date.today # Monday, March 5, 2012 puts date.cwyear # 2012 puts date.cweek # 10 (10th week of 2012) 

Now that I know what the current week is, I want to find out what the next week and the previous week are. I need to take the year (2012) and week number (10) and return it back to the date object so that I can calculate the value for the next / previous week. How can i do this?

+7
source share
5 answers

Do you want Date.commercial :

 require 'date' now = Date.today #=> 2012-03-05 monday_next_week = Date.commercial(now.cwyear,now.cweek+1) #=> 2012-03-12 next_sunday_or_today = monday_next_week - 1 #=> 2012-03-11 

Please note that the weeks start on Monday, so if you are on Sunday and ask for the next Monday - 1, you will receive the same day.

Note that if you do not want Mondays, you can also specify the day number in the method:

 thursday_next_week = Date.commercial(now.cwyear,now.cweek+1,4) #=> 2012-03-15 
+14
source

Day-based computing is pretty simple with Date objects. If you just want to get the previous / next week from this Date object, use the following:

 date = Date.today previous_week = (date - 7).cweek next_week = (date + 7).cweek 
+3
source

In ActiveSupport, you have an assistant for Fixnum conversion during http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Numeric/Time.html use:

 date = Date.today week_ago = date - 1.week next_week = date + 1.week 
+1
source

Assuming that you mean “this week’s current year number,” you can do the following:

2.weeks.since (Time.gm (Time.now.year)) => Fri Jan 15 00:00:00 UTC 2010 Replace (week_number - 1) for 1 in the above and you will get the date for the desired week.

0
source

I created several methods to get the week number of a given date, something like this:

 def self.get_week(date) year = date.year first_monday_of_the_year = self.get_first_monday_of_the_year(year) # The first days of January may belong to the previous year! if date < first_monday_of_the_year year -= 1 first_monday_of_the_year = self.get_first_monday_of_the_year(year) end day_difference = date - first_monday_of_the_year week = (day_difference / 7).to_i + 1 week end def self.get_monday_of_year_week(year, week) d = self.get_first_monday_of_the_year(year) d + ((week - 1) * 7).days end def self.get_first_monday_of_the_year(year) d = Date.new(year, 1, 7) # 7 Jan is always in the first week self.get_monday_of_week(d) end def self.get_monday_of_week(date) wday = (date.wday + 6) % 7 date - wday.days end 
0
source

All Articles