Skyalchemist
Skyalchemist

Reputation: 461

Rails display formatted date in words

I have the date in this format 2014-04-05 gotten from @post.date
I want to convert it to this format "Saturday Apr 5" in my view.
And if the date is today, i want it use this format "Today Apr 6" Currently i have

<% if @post.date === Date.today.strftime("%Y-%m-%d") %>
   <p> Today Month(short form) Day(number) </p>
<% else %>
   <p> Day(word) Month(short form) Day(number)  </p>
<% end %>

How do i go about formatting the dates?
Thanks in advance.

Upvotes: 0

Views: 2304

Answers (2)

Pierce
Pierce

Reputation: 1

A cleaner solution would be to implement this as a helper method in "app/helpers/application_helper.rb"

Define the method as such:

def date_string_for(datetime) datetime.strftime("%b %e, %Y") end

Then from any view you can call:

<%= date_string_for @post.date %>

This provides a DRY solution.

Upvotes: 0

Kirti Thorat
Kirti Thorat

Reputation: 53018

Use this:

<% if @post.date === Date.today %>
   <%= @post.date.strftime("Today %b %d") %>
<% else %>
   <%= @post.date.strftime("%A %b %d") %>
<% end %>

Refer to complete list of format directives available for strftime.

Upvotes: 5

Related Questions