Last active
December 28, 2015 10:21
-
-
Save vigram/8570ef05944a07182cc5 to your computer and use it in GitHub Desktop.
Find time difference(in months,years,weeks..etc) between two dates.
This file contains hidden or 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
=begin | |
Time difference (duration) in year, quarter, month, bi-week, week and day. | |
Usages: | |
TimeDifference.between(start_date, end_date).in_months | |
TimeDifference.between(start_date, end_date).in_years | |
=end | |
class TimeDifference | |
private_class_method :new | |
def self.between(start_date, end_date) | |
new(start_date, end_date) | |
end | |
def in_years | |
in_component("1.year") | |
end | |
def in_semi_year | |
in_component("6.months") | |
end | |
def in_quarters | |
in_component("3.months") | |
end | |
def in_months | |
in_component("1.month") | |
end | |
def in_bi_weeks | |
in_component("2.weeks") | |
end | |
def in_weeks | |
in_component("1.week") | |
end | |
def in_days | |
(@end_date - @start_date).to_i | |
end | |
private | |
def initialize(start_date, end_date) | |
@start_date = start_date | |
@end_date = end_date | |
end | |
def in_component(periods) | |
difference = 0 | |
next_dt = eval("@start_date + #{periods}") | |
while next_dt <= @end_date do | |
difference += 1 | |
next_dt = eval("next_dt + #{periods}") | |
end | |
difference | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment