Ruby: comparing dates of two Time objects

What is the best way to compare the dates of two Time objects in Ruby?

I have two objects, for example:

time_1 = Time.new(2012,12,10,10,10) time_2 = Time.new(2012,12,11,10,10) 

In this example, date comparison should return false.

Otherwise, the same date, but at different times, should return true:

 time_1 = Time.new(2012,12,10,10,10) time_2 = Time.new(2012,12,10,11,10) 

I tried using .to_date , which works for DateTime objects but is not supported by Time .

+6
source share
4 answers

Just require the "date" of the stdlib part, and then compare the dates:

 require "date" time1.to_date == time2.to_date 

The task is completed.

+6
source

I checked that this works for me:

 time_1.strftime("%F") == time_2.strftime("%F") 

The format %F returns only part of the date.

+3
source

Perhaps this is just a check:

 time_1.year == time_2.year && time_1.yday == time_2.yday 

This will be less resources than string comparisons.

monkey pathet class Time using this method, and I will be pleased to read

 class Time def date_compare(time) year == time.year && yday == time_2.yday end end time_1.date_compare time_2 
+3
source

to_date works fine in ruby ​​2.0 and ruby ​​1.9.3 and ruby ​​1.9.2 http://ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/Time.html

 >> time_1.to_date => #<Date: 2012-12-10 ((2456272j,0s,0n),+0s,2299161j)> 

but this is not in stdlib ruby ​​1.8.7 http://ruby-doc.org/stdlib-1.8.7/libdoc/time/rdoc/Time.html - but then your way of creating a time object does not work in this version:

 > time_1 = Time.new(2012,12,10,10,10) ArgumentError: wrong number of arguments (5 for 0) 
+1
source

Source: https://habr.com/ru/post/953969/


All Articles