Last active
September 10, 2018 23:32
-
-
Save yaauie/cfb8f3691d232b9ca2c5e5ac60cace51 to your computer and use it in GitHub Desktop.
A Ruby function for determining the number of whole years elapsed between two `Time` objects. No dependencies. MIT License.
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
## | |
# Determine the number of whole years elapsed between two [Time] objects. | |
# It is assumed that the provided [Time] objects are in the same time-zone | |
# and part of a single continuous chronology. | |
# | |
# @param time1 [Time] | |
# @param time2 [Time] | |
# | |
# @return [Integer] | |
# | |
# Copyright 2018 Ry Biesemeyer (@yaauie) | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining a copy | |
# of this software and associated documentation files (the "Software"), to deal | |
# in the Software without restriction, including without limitation the rights | |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
# copies of the Software, and to permit persons to whom the Software is | |
# furnished to do so, subject to the following conditions: | |
# | |
# The above copyright notice and this permission notice shall be included in | |
# all copies or substantial portions of the Software. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | |
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS | |
# IN THE SOFTWARE. | |
# | |
def years_elapsed(time1, time2) | |
fail(ArgumentError, "Invalid `time1` value `#{time1.inspect}` (expected a `Time` object)") unless time1.kind_of?(Time) | |
fail(ArgumentError, "Invalid `time2` value `#{time1.inspect}` (expected a `Time` object)") unless time2.kind_of?(Time) | |
# normalize order | |
time1, time2 = time2, time1 if time1 > time2 | |
years = time2.year - time1.year | |
[:month,:day,:hour,:min,:sec,:subsec].each do |precision| | |
case (time2.send(precision) - time1.send(precision)) | |
when 1 then return years | |
when -1 then return years -1 | |
end | |
end | |
return years | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment