Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Display summary of Ruby datetimes as range or as single day.
def formatted_datetime_range(start_datetime, end_datetime)
start_date = start_datetime.to_date rescue nil
end_date = end_datetime.to_date rescue nil
return "" if start_date.nil?
is_all_day = (start_datetime == start_datetime.beginning_of_day)
is_this_year = (start_datetime.year == Time.zone.today.year)
if end_date && start_date != end_date
if start_date.year == end_date.year
# Jan 14 - 15
# Jan 14 - 15, 2053
# Jan 14 - Feb 15
# Jan 14 - Feb 15, 2053
start_date.strftime("%b %-d") + " - " + end_date.strftime("#{'%b ' if start_date.month != end_date.month}%-d#{', %Y' unless is_this_year}")
else
# Jan 14, 2052 - Jan 15, 2053
# Jan 14, 2052 - Feb 15, 2053
start_date.strftime("%b %-d, %Y") + " - " + end_date.strftime("%b %-d, %Y")
end
else
# Tue, Jan 14
# Tue, Jan 14, 2053
# Tue, Jan 14 - 9:00am
# Tue, Jan 14, 2053 - 9:00am
start_datetime.strftime("%a, %b %-d#{', %Y' unless is_this_year}#{' - %l:%M%P' unless is_all_day}")
end
end
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.