0

I need to get the age of the article in days. For example, the article was written on Tue, 01 Apr 2014 18:31:07 EDT -04:00 and now I need the days from that date to now printed as an integer. How can I do so?

user3048402
  • 1,349
  • 1
  • 12
  • 29
  • 1
    This question is similar to [this one](http://stackoverflow.com/questions/9572860/rails-count-number-of-days-between-two-dates) which has several answers and a lengthy discussion. – Carlos Ramirez III Apr 25 '14 at 15:33

3 Answers3

0

With the Date class you can do

(Date.today - @article.created_at.to_date).to_i

to get the number of days between the two dates.

Zero Fiber
  • 4,417
  • 2
  • 23
  • 34
0

Please try something like this:

gem install time_diff

install the gem.

require 'time_diff'

time_diff_components = Time.diff(start_date_time, end_date_time)

time_diff_components[:year], time_diff_components[:month], time_diff_components[:week]

This will give more option.

More detail click

Jenorish
  • 1,694
  • 14
  • 19
0

This isn't the cleverest way, but it's probably the simplest: use a "magic number": 86400, which is the number of seconds in a day. (you probably already know there are 3600 seconds in an hour, mentally file this number alongside that)

Differences between Time/DateTime objects will be in seconds (as a float). If you divide this by 86400 you get the difference in days, as a float. You can then call to_i on this to get it as an integer if you want.

eg

((Time.now - @article.created_at)/86400).to_i

It's probably worth saving this as a constant, egs SECONDS_IN_A_DAY or something, to avoid mistyping.

Max Williams
  • 32,435
  • 31
  • 130
  • 197