2

So i want item to display to remaining on Items after 7 days the item will be deleted. ive tried

 <%= distance_of_time_in_words(item.created_at, item.created_at + 7.days) %> 

but all i get is "7 Days" on all items. Can anyone simply how this helper method works ?

Miguel Angel Quintana
  • 1,371
  • 2
  • 9
  • 12
  • 1
    So what you need is the difference from current time. So you should do it like this: `distance_of_time_in_words(Time.now, item.created_at + 7.days)`. If you try doing `2 - (2 + 7)` it will always return `-7` only and never change. – Deepesh Mar 15 '16 at 06:19
  • Thank little analogy helped loads thank you very much! – Miguel Angel Quintana Mar 15 '16 at 06:27

1 Answers1

5

Lets looks at the documentation to see what distance_of_time_in_words does:

distance_of_time_in_words(from_time, to_time = 0, options = {})
Reports the approximate distance in time between two Time, Date or DateTime objects or integers as seconds.

So it reports the time difference of the first argument and the second argument. Now, you're doing:

distance_of_time_in_words(item.created_at, item.created_at + 7.days)

The difference between item.created_at and item.created_at plus seven days is always ... seven days ;-)

I assume that this is something that will always be deleted after seven days? In that case, what you want, is the difference between the current date and the creation date plus seven days, which you can get with:

distance_of_time_in_words(Time.now, item.created_at + 7.days)
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
  • yeah thats what i was trying to get at , thank you . Dealing with Dates is just a little harder for me do deal with so this method mad my hair all mixed up. thank you for the explanation :) – Miguel Angel Quintana Mar 15 '16 at 06:31
  • @MiguelAngelQuintana Yeah, dates can be awkward. But they're just numbers. Many computers store the date as the number of seconds since 1st of January 1970 (it's currently 1458023724), and when you say `+ 7.days` you're really just doing a simple addition: `1458023724 + 86400 * 7` (one day has 86400 seconds, this is a useful number to memorize) and nothing more. Showing it as "Tue Mar 15 07:36:24 CET 2016" or "5 days and 6 hours" is really just a formatting thing for us poor humans, just like showing `125` seconds as `2:05` or `53.31` as `€53,31`... – Martin Tournoij Mar 15 '16 at 06:38