Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Humanizing time

I have a number of products that are perishable. Therefore, each product has an attribute called hours_expiration that tells how many hours the product can be used before it goes bad.

For ex, apple expires in 168 hours; nut expires in 4320 hours.

Given, the product's hours-to-expiration and the current time (Time.now or Date.now), how can I humanize the time-to-expiration in some of the following sample ways?

Your item is set to expire in about:

  • 6 months and 14 days
  • 1 month and 13 days
  • 1 month and 1 day
  • 27 days
  • 1 day
  • 23 hours
  • 1 hour
  • 50 minutes
  • 1 minute

Looking for something robust and simple!

like image 608
keruilin Avatar asked Mar 18 '11 14:03

keruilin


1 Answers

Another easy helper is time_ago_in_words: https://apidock.com/rails/ActionView/Helpers/DateHelper/time_ago_in_words

The method name might sound like it can only deal with past dates but actually it handles future dates just fine. You can try it in your rails console:

expiration_date = Time.now + 5.days 
puts "Expires in #{helper.time_ago_in_words(expiration_date)}"

"Expires in 5 days"

like image 155
snrlx Avatar answered Sep 28 '22 11:09

snrlx