Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the date for a given week number

Tags:

date

ruby

I am trying to do some date math 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 figure out what the next week and previous week are. I need to take the year (2012) and the week number (10) and turn it back into a date object so I can calculate the value for the next/previous week. How can I do this?

like image 460
Andrew Avatar asked Mar 05 '12 22:03

Andrew


People also ask

How do you convert a week number to a date in sheets?

How to get the date from a week number. To get the date of the Monday in a week, use =DATE( A1 , 1, -3 + 7 * B1 - WEEKDAY(DATE( A1 , 1, 4), 2) + 1) . Cell A1 contains the four-digit year (e.g. 2022), and cell B2 contains the week number (1-53).

How do you find the start date from the week?

Formula: =A2-WEEKDAY(A2,2)+1 Select a blank cell where you will return the beginning of week, and enter the formula =A2-WEEKDAY(A2,2)+1 (A2 is the cell with given date) into it, and drag the Fill Handle to the range as you need.


2 Answers

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

Note that weeks start on Monday, so if you are on a Sunday and ask for next monday - 1 you'll get the same day.

Note also that if you don't 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
like image 75
Phrogz Avatar answered Oct 08 '22 09:10

Phrogz


Calculating on a day basis is pretty simple with Date objects. If you just want to get the previous / next week from a given Date object use the following:

date = Date.today
previous_week = (date - 7).cweek
next_week = (date + 7).cweek
like image 40
Koraktor Avatar answered Oct 08 '22 09:10

Koraktor