How to get difference between two dates in days?

Hi,

I want to calculate difference between Current date & previous date
(stored in database). The difference should be in days. Hhow to do
that??
PLs tell me.

Thanx in advance.
Prash

Prashant T. <tiwari_p_k@…> writes:

I want to calculate difference between Current date & previous date
(stored in database). The difference should be in days. Hhow to do
that??

What about:

$ irb

require ‘date’
( Date.new(2006, 01, 02) - Date.new(2006, 01, 01) ).to_i
=> 1

?

Regards,
Marco

HI,
but when I am trying following into my view it giving me error:-

( Date.new(2006, 01, 02) - Date.new(2006, 01, 01) ).to_i

& error is:-

compile error
./script/…/config/…/app/views/comments/show.rhtml:74: syntax error
Date.new(2006, 01, 02) - Date.new(2006, 01, 01) ); _erbout.concat “\n”
^

Why I am getting this error?>
Thanx,
Prash

Marco L. wrote:

That was a pure Ruby snippet of code.

If you wish to calculate the difference between two dates in a View,
you have to write something like:

<%= ( @my_model.previous_date - Date.today() ).to_i %>

(assuming you’ve your model in an instance variable called ‘my_model’).

I’m a little rusty, but doesn’t erb want strings? Seems like I had to
put a .to_s on the
end of stuff like the above.

b

On 5/8/06, Ben M. [email protected] wrote:

Marco L. wrote:
I’m a little rusty, but doesn’t erb want strings? Seems like I had to put a .to_s on the
end of stuff like the above.

Well, my Rails doesn’t complain when I do <%= “50”.to_i %> at least.
(I just tried it). :slight_smile:

Mathias.

Prashant T. wrote:

Hi,

I want to calculate difference between Current date & previous date
(stored in database). The difference should be in days. Hhow to do
that??
PLs tell me.

Thanx in advance.
Prash

Have a look at the Rails API for the method distance_of_time_in_words

example: -

<%= distance_of_time_in_words(Time.now, record.created_on) %>

On 08/05/06, Prashant T. [email protected] wrote:

Date.new(2006, 01, 02) - Date.new(2006, 01, 01) ); _erbout.concat “\n”
^

Why I am getting this error?>

That was a pure Ruby snippet of code.

If you wish to calculate the difference between two dates in a View,
you have to write something like:

<%= ( @my_model.previous_date - Date.today() ).to_i %>

(assuming you’ve your model in an instance variable called ‘my_model’).

Marco

Huh. I don’t know what I was thinking of then… sorry for the noise.

b