< Return to Blog

Rails 3.1: Starting the Week on Sunday, as in the Middle East

Was rather interesting to find out that ‘Monday’ is hardcoded into Rails as the start of the week, so working around this involved creating a custom initialiser that reopened two classes as follows:

# based on
# https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/date/calculations.rb#L178
class Date
  def traditional_beginning_of_week
    days_to_sunday = self.wday!=0 ? self.wday : 0
    result = self - days_to_sunday.days
    self.acts_like?(:time) ? result.midnight : result
  end

  def traditional_end_of_week
    days_to_saturday = self.wday!=0 ? 6-self.wday : 0
    result = self + days_to_saturday.days
    self.acts_like?(:time) ? result.end_of_day : result
  end
end

class Time
  def traditional_beginning_of_week
    days_to_sunday = self.wday!=0 ? self.wday : 0
    result = self - days_to_sunday.days
    self.acts_like?(:time) ? result.midnight : result
  end

  def traditional_end_of_week
    days_to_saturday = self.wday!=0 ? 6-self.wday : 0
    result = self + days_to_saturday.days
    self.acts_like?(:time) ? result.end_of_day : result
  end
end

…and here’s the proof

pry(main)> Time.now.traditional_beginning_of_week
=> 2011-10-16 00:00:00 +0300
pry(main)> Time.now.traditional_end_of_week
=> 2011-10-22 23:59:59 +0300
pry(main)> Time.now.traditional_beginning_of_week.strftime('%e %A, %B %Y')
=> "16 Sunday, October 2011"
pry(main)> Time.now.traditional_end_of_week.strftime('%e %A, %B %Y')
=> "22 Saturday, October 2011"