2011-08-02 72 views

回答

6

我不知道你想要什麼......但也許你想是這樣的:

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

#> 4.42857142857143

+0

邁克爾你好,我想算算許多星期有一月,二月等... – andkjaer

+0

從星期日到星期日週一?因爲否則它總是4. 28/7是4. 30/7 = 4.29等 –

+0

不明白,有些飛蛾有5周,其他4對嗎?我可以計算嗎? – andkjaer

3

我需要知道多少個星期,包括部分一個月裏有一個星期。把它想成日曆中的行。你需要多少行?你必須考慮天數以及這個月的開始日期。例如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 
1

您可以使用以下方法:

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

0

使用寶石week_of_month

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

d.total_weeks 

=> 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 

GET號這樣

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

這回4