Format relative dates

Is there a ruby gem that will format dates relative to the current time? I want output like "Tomorrow at 5pm", "Thursday next week at 5:15pm", I'm not too concerned about the exact output, just as long as it's relative dates in natural language

Answers


if you have rails, I think ActionView::Helpers::DateHelper#distance_of_time_in_words helps that.

require 'rubygems'
require 'action_view'
include ActionView::Helpers::DateHelper

from_time = Time.now
distance_of_time_in_words(from_time, from_time + 50.minutes)        # => about 1 hour
distance_of_time_in_words(from_time, 50.minutes.from_now)           # => about 1 hour
distance_of_time_in_words(from_time, from_time + 15.seconds)        # => less than a minute
distance_of_time_in_words(from_time, from_time + 15.seconds, true)  # => less than 20 seconds
distance_of_time_in_words(from_time, 3.years.from_now)              # => over 3 years
distance_of_time_in_words(from_time, from_time + 60.hours)          # => about 3 days
distance_of_time_in_words(from_time, from_time + 45.seconds, true)  # => less than a minute
distance_of_time_in_words(from_time, from_time - 45.seconds, true)  # => less than a minute
distance_of_time_in_words(from_time, 76.seconds.from_now)           # => 1 minute
distance_of_time_in_words(from_time, from_time + 1.year + 3.days)   # => about 1 year
distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => over 4 years

to_time = Time.now + 6.years + 19.days
distance_of_time_in_words(from_time, to_time, true)     # => over 6 years
distance_of_time_in_words(to_time, from_time, true)     # => over 6 years
distance_of_time_in_words(Time.now, Time.now)           # => less than a minute

In case of relative to the current time, use distance_of_time_in_words_to_now instead of distance_of_time_in_words.

If your app is rails-based, just use distance_of_time_in_words, distance_of_time_in_words_to_now, time_ago_in_words in view.


try the gem 'chronic'

it does exactly what you ask.


Need Your Help

Do nothing when item is dropped in a list using JqueryUI

jquery jquery-ui

I'm using JqueryUI to drag and drop to a sortable list. Suppose coll-selected-list is the list I want to drop on, I want to check if the current item I'm dropping exists in the list already. If it ...

How to improve this Group by clause

sql sql-server

I am trying to make a report with the following SQL: