How to get difference between two dates in days?


#1

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


#2

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


#3

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


#4

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


#5

On 5/8/06, Ben M. removed_email_address@domain.invalid 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.


#6

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) %>


#7

On 08/05/06, Prashant T. removed_email_address@domain.invalid 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


#8

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

b