Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 such as:

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

In this example, the date comparison should return false.

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

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

I have tried to use .to_date that works for DateTime objects, but it is not supported by Time.

like image 643
Marco Avatar asked Sep 17 '13 07:09

Marco


2 Answers

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

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

Job done.

like image 116
d11wtq Avatar answered Sep 21 '22 21:09

d11wtq


I have verified that this works for me:

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

The %F format returns the date portion only.

like image 31
Ken Y-N Avatar answered Sep 19 '22 21:09

Ken Y-N