Skip to content

Instantly share code, notes, and snippets.

@croaky
Created October 15, 2009 15:53
Show Gist options
  • Save croaky/211045 to your computer and use it in GitHub Desktop.
Save croaky/211045 to your computer and use it in GitHub Desktop.
module DateTimeHelper
def format_date_range(date_range)
first = date_range.first
last = date_range.last
if same_day?(first, last)
"#{first.to_s(:month_day)}, #{first.year}"
elsif same_month?(first, last)
"#{first.to_s(:month_day)}-#{last.day}, #{last.year}"
else
"#{first.to_s(:month_day)}-#{last.to_s(:month_day)}, #{last.year}"
end
end
private
def same_day?(date_one, date_two)
date_one.day == date_two.day
end
def same_month?(date_one, date_two)
date_one.month == date_two.month
end
end
require 'test_helper'
class DateTimeHelperTest < ActionView::TestCase
should "format date range on same day" do
eight_oclock = DateTime.new(2009, 10, 12, 8)
nine_oclock = DateTime.new(2009, 10, 12, 9)
date_range = eight_oclock..nine_oclock
expected = "October 12, 2009"
assert_equal expected, format_date_range(date_range)
end
should "format date range on different days of same month" do
monday = DateTime.new(2009, 10, 12)
tuesday = DateTime.new(2009, 10, 13)
date_range = monday..tuesday
expected = "October 12-13, 2009"
assert_equal expected, format_date_range(date_range)
end
should "format date range on days of different months" do
october = DateTime.new(2009, 10, 31)
november = DateTime.new(2009, 11, 1)
date_range = october..november
expected = "October 31-November 1, 2009"
assert_equal expected, format_date_range(date_range)
end
end
<%= format_date_range(course.date_range) %>
{ :short_date => "%x", # 04/13/10
:long_date => "%a, %b %d, %Y", # Tue, Apr 13, 2010
:longer_date => "%B %d, %Y %H:%M %Z", # April 13, 2010 11:20
:index => "%Y/%m/%d %H:%M", # 2010/04/13 11:20
:standard => "%B %d, %Y", # April 13, 2010
:month_day => "%B %e", # April 13
:abbr_month => "%b" # Apr
}.each do |key, value|
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.update(
key => value
)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment