开发者

Rails number of weeks in month

开发者 https://www.devze.com 2023-03-24 07:20 出处:网络
How can I in rails calculate the number of weeks in a given mo开发者_如何学Cnth? Thanksi dont know exactly what you want... But maybe you want something like this:

How can I in rails calculate the number of weeks in a given mo开发者_如何学Cnth?

Thanks


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


def number_of_weeks_in_month
  4
end


Use the gem week_of_month

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

d.total_weeks

=> 5


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


Date.today.end_of_month.day/7
=> 4
0

精彩评论

暂无评论...
验证码 换一张
取 消