3

I need to Write rails helper method to return the most recent date.

So far this is my method

def latest_date(value_dates)
  value_dates.each  |value_date| do
  my_dates << value_date
end

I need to sort the above array and return just the latest date.

The date is in the following format:

2012-10-10T22:11:52.000Z

Is there a sort method for date?

4

1 回答 1

5

.max方法将为您完成;)

> [Date.today, (Date.today + 2.days) ].max
#=> Fri, 05 Jul 2013 

关于它的文档(Ruby 2.0):

您可能需要将数据解析为日期,如果它们是字符串,您可以使用:

dates = ["2012-10-10T22:11:52.000Z", "2012-11-10T22:11:52.000Z", "2013-10-10T22:11:52.000Z"]
dates = dates.map{ |date_str| Date.parse(date_str) }
dates.max #=> returns the maximum date of the Array

在我的 irb 控制台(Ruby 1.9.3)中查看:

> dates = ["2012-10-10T22:11:52.000Z", "2012-11-10T22:11:52.000Z", "2013-10-10T22:11:52.000Z"]
#=> ["2012-10-10T22:11:52.000Z", "2012-11-10T22:11:52.000Z", "2013-10-10T22:11:52.000Z"] 
> dates = dates.map{ |date_str| Date.parse(date_str) }
#=> [Wed, 10 Oct 2012, Sat, 10 Nov 2012, Thu, 10 Oct 2013] 
> dates.max
#=> Thu, 10 Oct 2013

DateTime.parse(date_str)如果你想保持时间也可以使用)

于 2013-07-03T20:27:31.227 回答