aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/date_and_time
diff options
context:
space:
mode:
authorGeorge Claghorn <george.claghorn@gmail.com>2015-01-04 20:01:26 -0500
committerGeorge Claghorn <george.claghorn@gmail.com>2015-01-06 05:42:37 -0500
commitadf5fc3b3c9b5774c0ad621ac3503d236b8ddd9c (patch)
tree2003d3b2f19a2404d1b03567b6a18bfb8b967d00 /activesupport/lib/active_support/core_ext/date_and_time
parentde4f40826e3b979735e4f3287725f1a7a3820818 (diff)
downloadrails-adf5fc3b3c9b5774c0ad621ac3503d236b8ddd9c.tar.gz
rails-adf5fc3b3c9b5774c0ad621ac3503d236b8ddd9c.tar.bz2
rails-adf5fc3b3c9b5774c0ad621ac3503d236b8ddd9c.zip
Add #on_weekend?, #next_weekday, and #prev_weekday methods to Date, Time, and DateTime
`#on_weekend?` returns true if the receiving date/time falls on a Saturday or Sunday. `#next_weekday` returns a new date/time representing the next day that does not fall on a Saturday or Sunday. `#prev_weekday` returns a new date/time representing the previous day that does not fall on a Saturday or Sunday.
Diffstat (limited to 'activesupport/lib/active_support/core_ext/date_and_time')
-rw-r--r--activesupport/lib/active_support/core_ext/date_and_time/calculations.rb25
1 files changed, 25 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
index b85e49aca5..4e86b270f9 100644
--- a/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
@@ -9,6 +9,7 @@ module DateAndTime
:saturday => 5,
:sunday => 6
}
+ WEEKEND_DAYS = [ 6, 0 ]
# Returns a new date/time representing yesterday.
def yesterday
@@ -35,6 +36,11 @@ module DateAndTime
self > self.class.current
end
+ # Returns true if the date/time falls on a Saturday or Sunday.
+ def on_weekend?
+ wday.in?(WEEKEND_DAYS)
+ end
+
# Returns a new date/time the specified number of days ago.
def days_ago(days)
advance(:days => -days)
@@ -116,6 +122,15 @@ module DateAndTime
first_hour(weeks_since(1).beginning_of_week.days_since(days_span(given_day_in_next_week)))
end
+ # Returns a new date/time representing the next weekday.
+ def next_weekday
+ if tomorrow.on_weekend?
+ next_week(:monday).change(hour: hour, min: min, sec: sec, usec: try(:usec))
+ else
+ tomorrow
+ end
+ end
+
# Short-hand for months_since(1).
def next_month
months_since(1)
@@ -140,6 +155,16 @@ module DateAndTime
end
alias_method :last_week, :prev_week
+ # Returns a new date/time representing the previous weekday.
+ def prev_weekday
+ if yesterday.on_weekend?
+ beginning_of_week(:friday).change(hour: hour, min: min, sec: sec, usec: try(:usec))
+ else
+ yesterday
+ end
+ end
+ alias_method :last_weekday, :prev_weekday
+
# Short-hand for months_ago(1).
def prev_month
months_ago(1)