Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find what week in a month a day is on?

I can't seem to wrap my head around what might be an easy question..

Suppose I have the date..

Fri, 14 Sep 2012 18:37:50 +0200

How do I find out what week this date is on for this month? Is it the 1st, the 2nd..? The third?

Thanks!

like image 210
Trip Avatar asked Sep 14 '12 16:09

Trip


2 Answers

Why use a library? Ruby has it by default:

Week number:
The week 1 of YYYY starts with a Sunday or Monday (according to %U
  or %W).  The days in the year before the first week are in week 0.
    %U - Week number of the year.  The week starts with Sunday.  (00..53)
    %W - Week number of the year.  The week starts with Monday.  (00..53)

> Time.zone.parse("2012-01-01").strftime("%U")
=> "01" 

So, given that we can find what week a given date is in the year, we can do some math to figure out what week of the month it occurs in.

> week_of_year_for_first_of_month = Time.zone.parse("2012-07-01").strftime("%U").to_i
> week_of_target_date = Time.zone.parse("2012-07-14").strftime("%U").to_i
> week_occurs_in = week_of_target_date - week_of_year_for_first_of_month + 1
> week_occurs_in # => 2

Or a method:

def week_of_month_for_date(date)
  my_date = Time.zone.parse(date)
  week_of_target_date = my_date.strftime("%U").to_i
  week_of_beginning_of_month = my_date.beginning_of_month.strftime("%U").to_i
  week_of_target_date - week_of_beginning_of_month + 1
end

> week_of_month_for_date("2012-07-14") # => 2 
> week_of_month_for_date("2012-07-15") # => 3 
like image 139
Jason Noble Avatar answered Oct 16 '22 03:10

Jason Noble


sachin87 has a library for determining such a thing.

like image 30
jornak Avatar answered Oct 16 '22 02:10

jornak