1

Much like this OP asked in Java, I'd like to know how to do in Ruby:

How to compare a date - String in the custom format “dd.MM.yyyy, HH:mm:ss” with another one?

I have these two strings, which convey dates and time and I would like to find the older one of the two:

20141024_133641 20141024_142440

The format is %Y%m%d_%H%M%S ; which makes the former the older one in this case.

Community
  • 1
  • 1
shaibn
  • 65
  • 1
  • 3
  • Sort them, first will be older, last -- newer ) – Yevgeniy Anfilofyev Oct 24 '14 at 12:04
  • Your format is simliar to that of [ISO 8601](http://devblog.avdi.org/2009/10/25/iso8601-dates-in-ruby/). If you can alter the format, consider using ISO 8601. One reason is that Ruby provides [Date#iso8601](http://www.ruby-doc.org/stdlib-2.1.1/libdoc/date/rdoc/Date.html) to convert the strings to `Date` objects. – Cary Swoveland Oct 24 '14 at 18:33

2 Answers2

9

Plain lexicographical string comparison will do the job here as your date strings are ordered from most significant to least significant (years to seconds) in strict order. If d1 is your first date and d2 is your second date string, then simple ruby will get the older one:

[d1,d2].min

kroky
  • 1,266
  • 11
  • 19
2

You could use DateTime.parse

 d1 = DateTime.parse("20141024_142440","%Y%m%d_%H%M%S")
 d2 = DateTime.parse("20141024_133641","%Y%m%d_%H%M%S")

and compare them as usual

 if d1 > d2 ...

or like @kroky said

[d1,d2].min.to_s #=> "2014-10-24T13:36:41+00:00"
[d1,d2].max.to_s #=> "2014-10-24T14:24:40+00:00"
Bala
  • 11,068
  • 19
  • 67
  • 120