Displaying dates for humans with human_date gem
I've just released a gem called human_date which makes it really easy to display dates in a human format in your Rails application.
I've been using these helpers for quite a while in different projects, so I decided to extract them into a gem.
With Date objects
date = Date.current # 2012-12-21 human_date(date) # Today human_date(date + 1.day) # Tomorrow human_date(date - 1.day) # Yesterday human_date(date - 2.days) # Dec 19 human_date(date - 1.year) # Dec 21, 2011
With Time objects
time = Time.now # 2012-08-28 17:20:54 human_time(time) # 5:20 pm # For Time objects, the default value for :today is `"%l:%M %p"` human_time(time - 1.day) # Yesterday
There is also a helper for creating HTML5
human_time_tag(date, pubdate: true) # <time datetime="2012-12-21" pubdate="pubdate">Today</time>
The default values are perfectly fine but if you want to customize the output, it is pretty easy.
human_date provides with five formats for Date and Time objects:
:current_yearby default shows the month and the date:
:other_yearby default shows the year as well:
Dec 21, 2011
You can easily customize them:
# config/locales/en.yml en: date: formats: today: "Today" tomorrow: "Tomorrow" yesterday: "Yesterday" current_year: "%h %e" other_year: "%h %e, %Y" time: formats: today: "%l:%M %p"
You might want to have different formats for different models, for example for a
Post published today you'll want to display
Today but for a
Comment you might want to be more precise and display the actual time:
This is easy to achieve with namespaces:
# config/locales/en.yml en: posts: time: formats: today: "Today" comments: time: formats: today: "%l:%M %p"
time = Time.now # 2012-08-28 17:20:54 human_time(time, :posts) # Today human_time(time, :comments) # 5:20 pm
Fork it at http://github.com/AlexanderZaytsev/human_date
You're the 8652nd person to read this article.