Skip to content

Instantly share code, notes, and snippets.

@sstarr
Last active December 24, 2015 15:09
Show Gist options
  • Save sstarr/6817534 to your computer and use it in GitHub Desktop.
Save sstarr/6817534 to your computer and use it in GitHub Desktop.
Split a date range into week long arrays with appropriate padding at the beginning and end to ensure that the weeks always start on Monday.
@from_date = Date.parse("1/10/2013")
@to_date = Date.parse("31/10/2013")
date_range = [*@from_date..@to_date]
prepend = (date_range)[0].wday # 2
append = (date_range)[-1].wday # 4
weeks = (date_range).unshift(*2..prepend).push(*2..append).each_slice(7).to_a
# [
# [0] [
# [0] 2,
# [1] Tue, 01 Oct 2013,
# [2] Wed, 02 Oct 2013,
# [3] Thu, 03 Oct 2013,
# [4] Fri, 04 Oct 2013,
# [5] Sat, 05 Oct 2013,
# [6] Sun, 06 Oct 2013
# ],
# [1] [
# [0] Mon, 07 Oct 2013,
# [1] Tue, 08 Oct 2013,
# [2] Wed, 09 Oct 2013,
# [3] Thu, 10 Oct 2013,
# [4] Fri, 11 Oct 2013,
# [5] Sat, 12 Oct 2013,
# [6] Sun, 13 Oct 2013
# ],
# [2] [
# [0] Mon, 14 Oct 2013,
# [1] Tue, 15 Oct 2013,
# [2] Wed, 16 Oct 2013,
# [3] Thu, 17 Oct 2013,
# [4] Fri, 18 Oct 2013,
# [5] Sat, 19 Oct 2013,
# [6] Sun, 20 Oct 2013
# ],
# [3] [
# [0] Mon, 21 Oct 2013,
# [1] Tue, 22 Oct 2013,
# [2] Wed, 23 Oct 2013,
# [3] Thu, 24 Oct 2013,
# [4] Fri, 25 Oct 2013,
# [5] Sat, 26 Oct 2013,
# [6] Sun, 27 Oct 2013
# ],
# [4] [
# [0] Mon, 28 Oct 2013,
# [1] Tue, 29 Oct 2013,
# [2] Wed, 30 Oct 2013,
# [3] Thu, 31 Oct 2013,
# [4] 2,
# [5] 3,
# [6] 4
# ]
# ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment