Rails number of weeks in month

青春壹個敷衍的年華 提交于 2020-01-01 09:01:41

问题


How can I in rails calculate the number of weeks in a given month?

Thanks


回答1:


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




回答2:


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



回答3:


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




回答4:


def number_of_weeks_in_month
  4
end



回答5:


Use the gem week_of_month

d = Date.new(2012,1,1)

d.total_weeks

=> 5



回答6:


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

get number of weeks for month like this

number_of_weeks_month(Date.parse("2017-11-01"),0,Date.parse("2017-11-30"))

this return 4



来源:https://stackoverflow.com/questions/6911045/rails-number-of-weeks-in-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!