Rails number of weeks in month
i dont know exactly what you want... But maybe you want something like this:
(Time::days_in_month(05,2010).to_f / 7)
#> 4.42857142857143
I needed to know how many weeks including partial weeks there were in a month. Think of it like rows in a calendar. How many rows do you need? You have to consider the number of days and also what day the month starts on. October 2011 actually has 6 unique weeks for example.
This is my answer (@date is the current date):
@week_count = (0.5 + (@date.at_end_of_month.day + @date.at_beginning_of_month.wday).to_f / 7.0).round
You can use the following methods:
WEEK_NUMBER_FORMAT = '%W'
# Returns the first day of month.
# If invoked without any arguments, this would return the
# first day of current month
def first_day_of_month(date_time=Time.now)
date_time.beginning_of_month
end
# Returns the last day of month.
# If invoked without any arguments, this would return the
# last day of current month
def last_day_of_month(date_time=Time.now)
date_time.end_of_month
end
# Returns the week number in the year in which the specified date_time lies.
# If invoked without any arguments, this would return the
# the week number in the current year
def week_number(date_time=Time.now)
date_time.strftime(WEEK_NUMBER_FORMAT).to_i
end
# Returns the number of weeks in the month in which the specified date_time lies.
# If invoked without any arguments, this would return the
# the number of weeks in the current month
def weeks_in_month(date_time=Time.now)
week_number(last_day_of_month(date_time)) - week_number(first_day_of_month(date_time)) + 1
end
Usage: weeks_in_month(date_time)
Hope it helps:
Thanks,
Jignesh