views:

88

answers:

2

In Rails, I find that timestamps in the console look different to the actual html view even when you have the same code. Unless I'm doing something really stupid:

>> article = News.first
=> #<News id: 1, title: "Testing", body: "yadda yadda", role_id: 1, created_at: "2009-04-12 05:33:07", updated_at: "2009-04-12 05:33:07">
>> article.created_at
=> Sun, 12 Apr 2009 05:33:07 UTC +00:00
>> article.created_at.to_date
=> Sun, 12 Apr 2009

And in the view:

<% for article in @news %>
    <% @current_date = article.created_at.to_date %>
    <% if @current_date != @date %>
     <%= @current_date %>
     <% @date = @current_date %>
    <% end %>

The output will be:

2009-04-14

Why are the formats different?

A: 

<%= calls to_s on the Date object, which results in 2009-04-14 no matter where it's called:

>> Date.today
=> Tue, 14 Apr 2009
>> Date.today.to_s
=> "2009-04-14"

I really don't know what gets called when you don't use to_s.

UPDATE: Now I know. If you don't use to_s or an equivalent, irb calls inspect on the date object:

>> Date.today.inspect
=> "Tue, 14 Apr 2009"

UPDATE 2:

You can replace @current_date with @current_date.to_s (or @current_date.to_s(:format)) in your view. Format can be short, long, db, long_ordinal, rfc822 or number.

You can also define a default date format in your application locale.

Can Berk Güder
see http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Date/Conversions.html#M001236
Can Berk Güder
+1  A: 

In config/initializers/time_formats.rb, write:

Time::DATE_FORMATS[:article] = "%a, %d %B %Y"
jonty