-
-
Save dawidof/b919429021f94b1b67ae41b41ed7c5fe to your computer and use it in GitHub Desktop.
Simple ruby date range splitter
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
class DateRangeSplitter | |
include Enumerable | |
def initialize(date_from, date_to, max_days, end_inclusive: true) | |
@date_from = date_from | |
@date_to = date_to | |
@max_days = max_days | |
@end_inclusive = end_inclusive | |
generate_split_dates | |
end | |
def each | |
return enum_for(:each) unless block_given? | |
@dates.each { |date_block| yield(date_block[0], date_block[1]) } | |
end | |
private | |
def generate_split_dates | |
start_date = @date_from | |
@dates = [] | |
begin | |
end_date = start_date + (@end_inclusive ? @max_days - 1 : @max_days).days | |
if end_date <= @date_to | |
@dates << [start_date, end_date] | |
else | |
@dates << [start_date, @date_to] | |
break | |
end | |
start_date = @end_inclusive ? end_date + 1.day : end_date | |
end while start_date <= @date_to | |
@dates | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As mentioned in this thread: https://stackoverflow.com/questions/9795391/is-there-a-standard-for-inclusive-exclusive-ends-of-time-intervals We should prefer inclusive start dates and exclusive end dates.
We can split a DateRange into days, weeks, months or years with the following tail recursive method:
This method takes
:days, :weeks, :months or :years
as a parameter. Notice that we rely on activesupport.