Ruby 格式化日期的函数

Ruby function to format date

我需要有关格式化日期字符串的帮助。我有一个 JSON 对象,其中包含元素 "start_date" 和 "end_date"。这些元素在字符串中包含日期信息,例如:

"2015-07-15"

我创建了这个方法来格式化我的 start_date 和 end_date:

def format_date(date)
  date.to_time.strftime('%b %d')
end

此方法的作用是将日期格式化为以下格式:

"Jul 15" 

此方法帮助我将 start_date 和 end_date 打印成以下形式:

"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

我将从这个开始,然后将其重构为对您而言更具可读性和可用性的内容。

我觉得你可以用 formatted_times gem

https://rubygems.org/gems/formatted_times/versions/0.0.4

它可以帮助您根据需要格式化日期