我如何在rails中计算给定月份的周数?
由于
答案 0 :(得分:6)
我不确切地知道你想要什么...但也许你想要这样的东西:
(Time::days_in_month(05,2010).to_f / 7)
#> 4.42857142857143
答案 1 :(得分:4)
我需要知道有多少周,包括一个月内的部分周。可以把它想象成日历中的行。你需要多少行?您必须考虑天数以及月份的开始日期。例如,2011年10月实际上有6个独特周。
这是我的回答(@date是当前日期):
@week_count = (0.5 + (@date.at_end_of_month.day + @date.at_beginning_of_month.wday).to_f / 7.0).round
答案 2 :(得分:2)
您可以使用以下方法:
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
用法:weeks_in_month(date_time)
希望有所帮助:
谢谢,
Jignesh
答案 3 :(得分:1)
def number_of_weeks_in_month
4
end
答案 4 :(得分:0)
使用gem week_of_month
d = Date.new(2012,1,1)
d.total_weeks
=> 5
答案 5 :(得分:0)
def number_of_weeks_month(start_of_month, count, end_of_month)
if start_date > end_of_month
return count
else
number_of_weeks_month(start_date.end_of_week + 1, count + 1, end_of_month)
end
end
获得像这样的月份周数
number_of_weeks_month(Date.parse("2017-11-01"),0,Date.parse("2017-11-30"))
这回归4
答案 6 :(得分:0)
Date.today.end_of_month.day/7
=> 4