Skip to content

Instantly share code, notes, and snippets.

@kanmaniselvan
Last active May 5, 2017 14:00
Show Gist options
  • Save kanmaniselvan/2a9337eb544aee860f86a9c898d2bcbb to your computer and use it in GitHub Desktop.
Save kanmaniselvan/2a9337eb544aee860f86a9c898d2bcbb to your computer and use it in GitHub Desktop.
Split date range by 'N' smaller ranges
def recursively_split_dates(start_date, end_date, dates_array, num_days_to_add)
if start_date >= end_date
last_date = dates_array.pop
dates_array << { start_date: last_date[:start_date], end_date: end_date }
else
start_date += num_days_to_add
dates_array << { start_date: dates_array.last[:end_date] + 1.day,
end_date: dates_array.last[:end_date] + num_days_to_add } if start_date <= end_date
recursively_split_dates(start_date, end_date, dates_array, num_days_to_add)
end
end
def split_date_range(start_date, end_date, split_number)
if 1 == split_number
return [{start_date: start_date, end_date: end_date}]
end
num_days_to_add = ((end_date - start_date).to_i / split_number).days
recursively_split_dates(start_date + num_days_to_add, end_date, [{start_date: start_date, end_date: start_date + num_days_to_add - 1.day}], num_days_to_add)
end
# ============= Example ================== #
start_date = Tue, 01 Mar 2016
end_date = Sun, 30 Apr 2017
# 1.
split_date_range(start_date, end_date, 2)
=> [
[0] {
:start_date => Tue, 01 Mar 2016,
:end_date => Wed, 28 Sep 2016
},
[1] {
:start_date => Thu, 29 Sep 2016,
:end_date => Sun, 30 Apr 2017
}
]
# 2.
split_date_range(start_date, end_date, 6)
=> [
[0] {
:start_date => Tue, 01 Mar 2016,
:end_date => Mon, 09 May 2016
},
[1] {
:start_date => Tue, 10 May 2016,
:end_date => Mon, 18 Jul 2016
},
[2] {
:start_date => Tue, 19 Jul 2016,
:end_date => Mon, 26 Sep 2016
},
[3] {
:start_date => Tue, 27 Sep 2016,
:end_date => Mon, 05 Dec 2016
},
[4] {
:start_date => Tue, 06 Dec 2016,
:end_date => Mon, 13 Feb 2017
},
[5] {
:start_date => Tue, 14 Feb 2017,
:end_date => Sun, 30 Apr 2017
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment