Last active
August 29, 2015 14:04
-
-
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)
This file contains hidden or 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
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 |
This file contains hidden or 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
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, this doesn't do
year–year
, but that could be easily added.