Skip to content

Instantly share code, notes, and snippets.

@coryschires
Created July 6, 2010 18:13
Show Gist options
  • Select an option

  • Save coryschires/465727 to your computer and use it in GitHub Desktop.

Select an option

Save coryschires/465727 to your computer and use it in GitHub Desktop.
def formatted_date_range(start_date, end_date = nil)
if start_date && end_date
same_month = start_date.month == end_date.month
same_year = start_date.year == end_date.year
date = "#{start_date.strftime("%B %e")} - #{end_date.strftime("%e, %Y")}" if same_month && same_year
date = "#{start_date.strftime("%B %e")} - #{end_date.strftime("%B %e, %Y")}" if !same_month && same_year
date = "#{start_date.strftime("%B %e, %Y")} - #{end_date.strftime("%B %e, %Y")}" if !same_year
else
date = start_date.strftime("%A, %B %e, %Y")
end
date
end
# rspec tests
describe "formatted date range" do
it "should print just start date if no end date is provided" do
start_date = Date.parse("January 01 2010")
formatted_date_range(start_date).should match("Friday,\s+January\s+1,\s+2010")
end
it "should only show year once if start date has the same year as end date" do
start_date = Date.parse("January 01 2010")
end_date = start_date + 2.months
formatted_date_range(start_date, end_date).should match("January\s+1\s+-\s+March\s+1,\s+2010")
end
it "should show years from both start and end date if the dates have different years" do
start_date = Date.parse("January 01 2010")
end_date = start_date + 2.years
formatted_date_range(start_date, end_date).should match(/January\s+1,\s+2010\s+-\s+January\s+1,\s+2012/)
end
it "should only show month once if start date has the same month as end date" do
start_date = Date.parse("January 01 2010")
end_date = start_date + 3.days
formatted_date_range(start_date, end_date).should match(/January\s+1\s+-\s+4,\s+2010/)
end
it "should show months from both start and end date if the dates have different months" do
start_date = Date.parse("January 01 2010")
end_date = start_date + 2.months
formatted_date_range(start_date, end_date).should match(/January\s+1\s+-\s+March\s+1,\s+2010/)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment