Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way in ruby to get the later of two dates?

just curious - is there a shorter way to achieve this?

latest_date = date1 > date2 ? date1 : date2 

thanks

like image 226
Greg Avatar asked Feb 28 '12 03:02

Greg


People also ask

How do I get yesterday's Date in Ruby?

You can just subtract 86400 from a Time object to get one day before. If you are using Rails, or have ActiveSupport included, you can replace 86400 with 1. days . If you're using a Date object, and not a Time object, just subtract 1 from it.

How do I get the last day of the month in Ruby?

new(y, m, d) , you can create a new Date object. The values for day (d) and month (m) can be negative in which case they count backwards from the end of the year and the end of the month respectively.

How do I get a timestamp in Ruby?

The proper way is to do a Time. now. getutc. to_i to get the proper timestamp amount as simply displaying the integer need not always be same as the utc timestamp due to time zone differences.

How do you parse a Date in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.


1 Answers

Use Enumerable#max:

latest_date = [date1, date2].max 
like image 183
Niklas B. Avatar answered Sep 28 '22 00:09

Niklas B.