Skip to content

Instantly share code, notes, and snippets.

@madrobby
Last active August 29, 2015 14:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save madrobby/e78cd94e7d4ad374e0ac to your computer and use it in GitHub Desktop.
Save madrobby/e78cd94e7d4ad374e0ac to your computer and use it in GitHub Desktop.
Format date ranges according to the Wikipedia styleguide (http://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style/Dates_and_numbers#Ranges)
def format_date_range(from, to)
to = from if to.nil?
return '' if from.nil? && to.nil?
from, to = to, from if to < from
if from == to
from.strftime('%B %e, %Y')
elsif from.year == to.year && from.month == to.month &&
from.beginning_of_month == from && to.end_of_month == to
from.strftime('%B %Y')
elsif from.year == to.year &&
from.beginning_of_month == from && to.end_of_month == to
"#{from.strftime('%B')}#{to.strftime('%B %Y')}"
elsif from.beginning_of_month == from && to.end_of_month == to
"#{from.strftime('%B %Y')}#{to.strftime('%B %Y')}"
elsif from.year == to.year && from.month == to.month
"#{from.strftime('%B %e')}#{to.strftime('%e, %Y')}"
elsif from.year == to.year
"#{from.strftime('%B %e')}#{to.strftime('%B %e, %Y')}"
else
"#{from.strftime('%B %e, %Y')}#{to.strftime('%B %e, %Y')}"
end.gsub(/\s{2,}/,' ')
end
# date ranges, including year threshold and full month
assert_equal "April 2–17, 2014",
format_date_range(Date.new(2014,4,2),Date.new(2014,4,17))
assert_equal "December 13, 2013 – January 4, 2014",
format_date_range(Date.new(2013,12,13),Date.new(2014,1,4))
assert_equal "May–June 2014",
format_date_range(Date.new(2014,5,1),Date.new(2014,6,30))
assert_equal "October 2013 – June 2014",
format_date_range(Date.new(2013,10,1),Date.new(2014,6,30))
assert_equal "April 2014",
format_date_range(Date.new(2014,4,1),Date.new(2014,4,30))
# dates in reverse order
assert_equal "April 2–17, 2014",
format_date_range(Date.new(2014,4,17),Date.new(2014,4,2))
assert_equal "December 13, 2013 – January 4, 2014",
format_date_range(Date.new(2014,1,4),Date.new(2013,12,13))
assert_equal "April 2014",
format_date_range(Date.new(2014,4,30),Date.new(2014,4,1))
# same day
assert_equal "April 4, 2014",
format_date_range(Date.new(2014,4,4),Date.new(2014,4,4)
@madrobby
Copy link
Author

Note, this doesn't do year–year, but that could be easily added.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment