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!
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
sachin87 has a library for determining such a thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With