Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails helper function to return the most recent date

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?

like image 508
newbie Avatar asked Dec 03 '25 23:12

newbie


1 Answers

The .max method will do it for you ;)

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

Documentation about it (Ruby 2.0):

  • http://ruby-doc.org/core-2.0/Enumerable.html#method-i-max

You may need to parse the data into Dates, if they are strings, you can use:

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

See in my irb console (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

(use DateTime.parse(date_str) if you want to keep the Time also)

like image 158
MrYoshiji Avatar answered Dec 05 '25 12:12

MrYoshiji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!