用于格式化日期的Ruby函数
我需要格式化日期字符串的帮助。我有一个JSON对象,其中包含元素“开始日期”和“结束日期”。这些元素以字符串形式包含日期信息,例如:用于格式化日期的Ruby函数,ruby,date,methods,format,Ruby,Date,Methods,Format,我需要格式化日期字符串的帮助。我有一个JSON对象,其中包含元素“开始日期”和“结束日期”。这些元素以字符串形式包含日期信息,例如: "2015-07-15" 我已创建此方法来格式化我的开始日期和结束日期: def format_date(date) date.to_time.strftime('%b %d') end 此方法的作用是将日期格式化为以下格式: "Jul 15" 此方法帮助我将开始日期和结束日期打印到表单中: "Jul 15 to Jul 27" 我想要的是将我的日
"2015-07-15"
我已创建此方法来格式化我的开始日期和结束日期:
def format_date(date)
date.to_time.strftime('%b %d')
end
此方法的作用是将日期格式化为以下格式:
"Jul 15"
此方法帮助我将开始日期和结束日期打印到表单中:
"Jul 15 to Jul 27"
我想要的是将我的日期格式化为:
"15 - 27 July 2015" #If the two dates fall within the same month
"15 July - 27 Aug 2015" #If the two dates fall into separate months
有人能帮我写这样一个ruby方法吗?你是说这样的吗
def format_date(date1, date2)
# convert the dates to time
date1 = date1.to_time
date2 = date2.to_time
# Ensure date1 is the lowest
if date1 > date2
date1, date2 = date2, date1
end
# handle identical dates
if date1 == date2
return date1.strftime('%d %b %Y')
end
# handle same year
if date1.year == date2.year
#handle same month
if date1.month == date2.month
return "#{date1.strftime('%d')} - #{date2.strftime('%d %b %Y')}"
# handle different month
else
return "#{date1.strftime('%d %b')} - #{date2.strftime('%d %b %Y')}"
end
end
# handle different date-month-year
return "#{date1.strftime('%d %b %Y')} - #{date2.strftime('%d %b %Y')}"
end
我将从这个开始,并将其重构为更可读、更有用的内容。我认为您可以使用格式化的gem
它可以帮助您根据您的要求设置日期格式我认为您必须在这里处理几种情况:(1)同一天,(2)不同的天但同一个月和同一年,(3)不同的月但同一年(4)不同的年。非常感谢!你真的救了我几个小时伤脑筋!我真的很感激!再次感谢!