Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Jul 26, 2014

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
You can’t perform that action at this time.