5

Is there a rails helper opposite of time_ago_in_words ? I can't seem to find the opposite...where I can have 7 days from now converted to "in about 1 week".

I can get this to work for the past:

 <%= time_ago_in_words( milestone.due_date) %>

But this doesn't work for the future:

   <%= time_ahead_in_words(milestone.due_date) %>

stumped.

NothingToSeeHere
  • 2,253
  • 5
  • 25
  • 57

4 Answers4

5

You can use distance_of_time_in_words(from_time, to_time = 0, options = {}) instead.

So you could set it up like so:

<%= distance_of_time_in_words(Time.now, milestone.due_date) %>

Collin Graves
  • 2,207
  • 15
  • 11
2

Sounds like you're in need of the "distance_in_time" helper method.

Ex.

    from_time = Time.current
helper.distance_of_time_in_words(from_time, from_time + 50.minutes)

=>about 1 hour

More specifically, in your case you would do:

from_time = Time.current
    helper.distance_of_time_in_words(from_time, from_time + 6.days)

    =>about 7 days
bkunzi01
  • 4,504
  • 1
  • 18
  • 25
1

You can use distance_of_time_in_words. For example:

distance_of_time_in_words(Time.current, milestone.due_date)

would be equivalent to your time_ahead_in_words pseudo code.

See distance_of_time_in_words documentation for details.

boulder
  • 3,256
  • 15
  • 21
0

distance_of_time_in_words is what you're after. Be aware that:

  1. distance_of_time_in_words doesn't assume you mean from now, so you have to tell it that with Time.current. E.g.
appointment_start_time = ActiveSupport::TimeZone['Sydney'].parse("2022-11-14 07:00:00 UTC")
distance_of_time_in_words(Time.current, appointment_start_time)
=> "about 2 years"
  1. distance_of_time_in_words will still return a result if the time was in the past, so beware of that!

  2. if using distance_of_time_in_words in the rails console, you need to prepend helper., like so:

helper.distance_of_time_in_words(Time.current, appointment_start_time)
=> "about 2 years"

References:

stevec
  • 41,291
  • 27
  • 223
  • 311