Monday, August 23, 2010

Finding time difference in Ruby

Finding time difference between two dates or times is very simple in ruby. It is just like doing arithmetic subtraction. We can do it for different formats in the following way:

Date
d1 = Date.parse("2010-08-23")
d2 = Date.parse("2010-08-24")
day_diff = (d2 - d1).to_i     # returns number of days

DateTime
dt1 = DateTime.strptime("2009/04/16 19:52:30", "%Y/%m/%d %H:%M:%S").to_time
dt2 = DateTime.strptime("2009/04/17 19:52:30", "%Y/%m/%d %H:%M:%S").to_time
time_diff = dt2-dt1    # returns time difference in seconds

Time
t1 = Time.parse("2010-08-24 01:20:00")
 t2 = Time.parse("2010-08-24 05:20:00")
time_diff =  t2-t1        # returns time difference in seconds

No comments: