Showing posts with label date difference in ror. Show all posts
Showing posts with label date difference in ror. Show all posts

Tuesday, March 3, 2009

Calculate date difference in ror

For example if you have a @date1 and @date2, and you want a difference between them

@date1 = {firstdate}
@date2 = {Seconddate}
@diff = (@date2.to_date - @date1.to_date).to_i

And you will get a difference in integer. :)

The code given below is explaining the subtraction of timestamp and date.

A timestamp is probably a Time and subtraction gives the number of
seconds between the two. If you convert to Date, subtraction gives
days.

>> Time.now - 18.seconds.ago
=> 17.999993
>> Time.now - 3.days.ago
=> 259199.999989

>> Date.today
=> #
>> Date.today.to_s
=> "2007-06-18"
>> 3.days.ago.to_date.to_s
=> "2007-06-15"

>> Time.now.to_date - 3.days.ago.to_date
=> Rational(3, 1)
>> (Time.now.to_date - 3.days.ago.to_date).to_i
=> 3
>> (Date.today - 3.days.ago.to_date)
=> Rational(3, 1)
>> (Date.today - 3.days.ago.to_date).to_i
=> 3