Рельсы количество недель в месяце - PullRequest
8 голосов
/ 02 августа 2011

Как я могу в рельсах рассчитать количество недель в данном месяце?

Спасибо

Ответы [ 6 ]

6 голосов
/ 02 августа 2011

Я не знаю точно, что вы хотите ... Но, может быть, вы хотите что-то вроде этого:

(Time::days_in_month(05,2010).to_f / 7)

#> 4.42857142857143

4 голосов
/ 03 октября 2011

Мне нужно было знать, сколько недель, включая неполные недели, было в месяце.Думайте об этом как строки в календаре.Сколько строк вам нужно?Вы должны учитывать количество дней, а также день начала месяца.Например, октябрь 2011 года имеет 6 уникальных недель.

Это мой ответ (@date - текущая дата):

@week_count = (0.5 + (@date.at_end_of_month.day + @date.at_beginning_of_month.wday).to_f / 7.0).round
2 голосов
/ 18 мая 2012

Вы можете использовать следующие методы:

  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

Использование: days_in_month (date_time)

Надеюсь, это поможет:

Спасибо,

Jignesh

1 голос
/ 11 июля 2019
def number_of_weeks_in_month
  4
end
0 голосов
/ 08 ноября 2017
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

0 голосов
/ 26 июля 2012

Используйте драгоценный камень week_of_month

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

d.total_weeks

=> 5
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...