TheNoviceAllen TheNoviceAllen - 5 months ago 21
Ruby Question

Return an Integer between 1 and 52, based on a given Date

I have a client that's giving me data sets that are broken down into quarters, periods (a block of four weeks in a quarter), and weeks. I'm writing a quick reference algorithm to return the quarter, period, week given a date and year and vise versa.

Their data is always broken down into 52 weeks, where week 1 always contains Jan 1st and starts with the Monday before or at Jan 1st. This is how they handle the 365 / 7 = 52.142857 conundrum.

So, is there a gem or built in function (cweek returns 1-53), that would give me a week number based on the premise that week 1 always contains Jan 1st or do I need to design something additional?

Answer

Way 1. Date#strftime

Date.new(2016,1,1).strftime("%U").to_i + 1 # week starts with Sunday
Date.new(2016,1,1).strftime("%W").to_i + 1 # week starts with Monday

Way 2. Date#cweek

Date.new(2016,1,1).cweek % 53 + 1 # week starts with Monday
Comments