Last active
December 18, 2015 02:08
-
-
Save joekhoobyar/5708504 to your computer and use it in GitHub Desktop.
Date/Time extensions calculating various permutations of dates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'date' | |
module DateExtensions | |
WEEKDAYS = { :sunday => 0, :monday => 1, :tuesday => 2, :wednesday => 3, | |
:thursday => 4, :friday => 5, :saturday => 6 } | |
# Returns the first weekday of the month. | |
def first_wday | |
(wday - day + 1) % 7 | |
end | |
# Returns the day of the month for the +(n\+1)+-th weekday +d+ of this month. The first week is +0+. | |
def day_of_nwday(n,d) | |
1 + (d - (wday - day + 1)) % 7 + n * 7 | |
end | |
# Returns the day of the month for the +(n)+-th weekday +d+ of this month. | |
# If not supplied, +d+ defaults to wday. The first week is +1+. | |
def day_of_nth_wday(n,d=wday) | |
day_of_nwday n-1, WEEKDAYS[d]||d | |
end | |
# Returns an instance representing the soonest +(n)+-th weekday +d+ of month +m+, | |
# such that +new_instance >= self+ _and_ +new_instance < self.next_year+. | |
# If not supplied, +d+ defaults to wday, and +m+ defaults to month. | |
def soonest_nth_wday_of_month(n,d=wday,m=month) | |
m = month + 12 if m == month && day_of_nth_wday(n,d) < day | |
months_since(m - month).at_nth_wday(n, d) | |
end | |
alias soonest_nth_wday soonest_nth_wday_of_month | |
# Week of the year, starting at zero. | |
def yweek | |
(yday - wday) / 7 + 1 | |
end | |
# Week of the month, starting at zero. | |
def mweek | |
(5 - wday + day) / 7 | |
end | |
# Return the day name. | |
def day_name | |
Date::DAYNAMES[wday] | |
end | |
# Return the abbreviated day name. | |
def abbr_day_name | |
Date::ABBR_DAYNAMES[wday] | |
end | |
# Return the month name. | |
def month_name | |
Date::MONTHNAMES[month] | |
end | |
# Return the abbreviated month name. | |
def abbr_month_name | |
Date::ABBR_MONTHNAMES[month] | |
end | |
end | |
class Date | |
include DateExtensions | |
# Returns a new instance for the day of this month returned by +day_of_nwday+. | |
def at_nwday(n,d=wday) | |
self + day_of_nwday(n, d) - day | |
end | |
# Returns a new instance for the day of this month returned by +day_of_nth_wday+. | |
def at_nth_wday(n,d=wday) | |
self + day_of_nth_wday(n, d) - day | |
end | |
end | |
class Time | |
include DateExtensions | |
# Returns a new instance for the day of this month returned by +day_of_nwday+. | |
def at_nwday(n,d=wday) | |
self + day_of_nwday(n, d).days - day.days | |
end | |
# Returns a new instance for the day of this month returned by +day_of_nth_wday+. | |
def at_nth_wday(n,d=wday) | |
self + day_of_nth_wday(n, d).days - day.days | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment