aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/date/calculations.rb
diff options
context:
space:
mode:
authorgregolsen <anotheroneman@yahoo.com>2011-11-06 21:42:03 +0200
committerXavier Noria <fxn@hashref.com>2011-11-25 12:02:49 -0800
commit3f1a4c3415113f2d365eb1a5531757699afec605 (patch)
tree8f4a5c4306ad199f6a64b4970b0200eda58471df /activesupport/lib/active_support/core_ext/date/calculations.rb
parent0a4035b12a6c59253cb60f9e3456513c6a6a9d33 (diff)
downloadrails-3f1a4c3415113f2d365eb1a5531757699afec605.tar.gz
rails-3f1a4c3415113f2d365eb1a5531757699afec605.tar.bz2
rails-3f1a4c3415113f2d365eb1a5531757699afec605.zip
beginning_of_week extended in both Time and Date so that to return week start based on start day that is monday by default
Diffstat (limited to 'activesupport/lib/active_support/core_ext/date/calculations.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/date/calculations.rb24
1 files changed, 16 insertions, 8 deletions
diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb
index c6d5f29690..a322075c4e 100644
--- a/activesupport/lib/active_support/core_ext/date/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date/calculations.rb
@@ -174,19 +174,27 @@ class Date
months_since(1)
end unless method_defined?(:next_month)
- # Returns a new Date/DateTime representing the "start" of this week (i.e, Monday; DateTime objects will have time set to 0:00).
- def beginning_of_week
- days_to_monday = self.wday!=0 ? self.wday-1 : 6
- result = self - days_to_monday
+ # Returns number of days to start of this week, week starts on start_day (default is Monday)
+ def days_to_week_start(start_day = :monday)
+ start_day_number = DAYS_INTO_WEEK[start_day]
+ current_day_number = wday != 0 ? wday - 1 : 6
+ days_span = current_day_number - start_day_number
+ days_span >= 0 ? days_span : 7 + days_span
+ end
+
+ # Returns a new Date/DateTime representing the "start" of this week, week starts on start_day (i.e, Monday; DateTime objects will have time set to 0:00).
+ def beginning_of_week(start_day = :monday)
+ days_to_start = days_to_week_start(start_day)
+ result = self - days_to_start
self.acts_like?(:time) ? result.midnight : result
end
alias :monday :beginning_of_week
alias :at_beginning_of_week :beginning_of_week
- # Returns a new Date/DateTime representing the end of this week (Sunday, DateTime objects will have time set to 23:59:59).
- def end_of_week
- days_to_sunday = self.wday!=0 ? 7-self.wday : 0
- result = self + days_to_sunday.days
+ # Returns a new Date/DateTime representing the end of this week, week starts on start_day (Sunday, DateTime objects will have time set to 23:59:59).
+ def end_of_week(start_day = :monday)
+ days_to_end = 6 - days_to_week_start(start_day)
+ result = self + days_to_end.days
self.acts_like?(:time) ? result.end_of_day : result
end
alias :sunday :end_of_week