DEV Community

Shkuryn
Shkuryn

Posted on

The Magic of Time in Rails: Journey into the Past with time_ago_in_words

Web development projects take on a life of their own, and so does time. In the world of Ruby on Rails there is a wonderful method that can give character to your time - time_ago_in_words. Let's embrace this magic and create dynamic, engaging experiences for your users.
Journey to the Past:

When your site posts get older than dinosaurs, regular timestamps turn into boring numbers. However, with time_ago_in_words you can offer your users more than just "2 minutes ago" or "yesterday".

How it works:

This method translates ordinary timestamps into magic phrases, providing dynamic descriptions of time, such as "A moment ago," "An hour ago," or even "Last month." Your interface becomes more alive, and users feel that your messages not only exist in space, but are themselves a part of time.

time_ago_in_words(3.minutes.from_now)                 # => 3 minutes
time_ago_in_words(3.minutes.ago)                      # => 3 minutes
time_ago_in_words(Time.now - 15.hours)                # => about 15 hours
time_ago_in_words(Time.now)                           # => less than a minute
time_ago_in_words(Time.now, include_seconds: true) # => less than 5 seconds

from_time = Time.now - 3.days - 14.minutes - 25.seconds
time_ago_in_words(from_time)      # => 3 days

from_time = (3.days + 14.minutes + 25.seconds).ago
time_ago_in_words(from_time)      # => 3 days
Enter fullscreen mode Exit fullscreen mode

Features and Settings:

The time_ago_in_words method automatically adapts to different languages and can be customized to suit your preferences. You can use it to create a friendly and interesting user experience.

About alias:

The time_ago_in_words method in Ruby on Rails is not alone in its magic. He has his close ally, a synonym, ready to share with him the protection of time - distance_of_time_in_words_to_now. Both methods have the unique ability to transform cold time numbers into lively phrases, immersing your applications in the world of human time perception. So, when creating dynamic user interfaces or visualizing timestamps, you can choose one of these methods, knowing that each is capable of recreating the sense of time with a unique elegance.

Top comments (0)