Formatting a date object to display a human readable date

sergserg picture sergserg · Aug 7, 2012 · Viewed 35.8k times · Source

Here's what I'd like to display:

May 13, 2012

Here's what is being displayed:

2012-05-13

I searched for some answers and it led me to "Formatting Dates and Floats in Ruby", where it mentions a possible solution:

<p class="date"><%= @news_item.postdate.to_s("%B %d, %Y") %></p>

However this doesn't change the output at all. No debugging errors, or exceptions are fired.

I can do this and it works perfectly fine:

<p class="date"><%= Time.now.to_s("%B %d, %Y") %></p>

Here is my migration file (to see what data type I used):

class CreateNewsItems < ActiveRecord::Migration
  def change
    create_table :news_items do |t|

      t.date :postdate

      t.timestamps
    end
  end
end

Answer

Casper picture Casper · Aug 7, 2012

Date.to_s is not the same as Time.to_s. Your postdate is a Date, so therefore you might want to look at strftime instead:

postdate.strftime("%B %d, %Y")

Or even look to add your own custom date format to your Rails app:
Need small help in converting date format in ruby