0

I just wonder how the date period can be written in Ruby?

date_a = Time.at() # <= new
date_b = Time.at() # <= old

I'd love to have something like: September 1 - 30, 2016

Also it needs to be considered the year. (Ex. if it's in January,

It should be December 25 2016 - January 25 2017)

1 Answer 1

4

You could do something like this

def format_dates(*dates)
  date1, date2 = dates.sort
  return "#{date1.strftime("%B %d %Y")} if date1 == date2

  if date1.year == date2.year
    if date1.month == date2.month
      "#{date1.strftime("%B")} #{date1.day} - #{date2.day}, #{date1.year}"
    else
      "#{date1.strftime("%B %d")} - #{date2.strftime("%B %d")}, #{date1.year}"
    end
  else
    "#{date1.strftime("%B %d %Y")} - #{date2.strftime("%B %d %Y")}"
  end
end

p format_dates(Date.parse('25/12/2016'), Date.parse('25/01/2017')) 
# => "December 25 2016 - January 25 2017"
p format_dates(Date.parse('25/12/2016'), Date.parse('25/01/2016')) 
# => "January 25 - December 25, 2016"
1
  • I don't recall ever seeing "January 25 - December 25, 2016". I think there are only two cases: same month and year or not the same month and year. The modification would be trivial, of course. Upvoted. Nov 22, 2016 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.