Module: Blackcal::TimeUtil

Defined in:
lib/blackcal/time_util.rb

Overview

Time utils module

Class Method Summary collapse

Class Method Details

.week_of_month(date_or_time, start_day = :sunday) ⇒ Integer

Returns the week of month

Returns:

  • (Integer)

    week of month

See Also:



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/blackcal/time_util.rb', line 9

def self.week_of_month(date_or_time, start_day = :sunday)
  date = date_or_time.to_date
  week_start_format = start_day == :sunday ? '%U' : '%W'

  week_of_month_start = Date.new(date.year, date.month, 1)
  week_of_month_start_num = week_of_month_start.strftime(week_start_format).to_i
  # Skip first week if doesn't contain a Thursday
  week_of_month_start_num += 1 if week_of_month_start.wday > 4

  month_week_index = date.strftime(week_start_format).to_i - week_of_month_start_num
  month_week_index + 1 # Add 1 so that first week is 1 and not 0
end