16

This should be a simple thing. Well, Im sure it should be simple, this is rails.

The problem is: in the model all data has a field created_at. to retrieve this info in the view I use a block, where is a line t.created_at.

It shows me a result like 2015-04-12 11:04:44 UTC

Which method should I use to show this date as 2015-04-12? As I suppose it should be something like that: t.created_at.date_only

Could you help me?

Neon_10
  • 711
  • 2
  • 7
  • 19

4 Answers4

38

You can read more about strftime here

t.created_at.strftime("%Y-%m-%d")
Mihail Petkov
  • 1,535
  • 11
  • 11
16

And it can be done even easier way:

t.created_at.to_date
Tsvetkova Maria
  • 161
  • 1
  • 3
  • 3
    sorry for asking simple questions, but : where do you put that ? in application_controller ? – thiebo Mar 01 '17 at 13:32
2

Or with locales:

// view:
<% @articles.each do |c| %>
    <%= l c.created_at.to_date, format: :short %>
<% end %>
thiebo
  • 1,339
  • 1
  • 17
  • 37
1

Sometimes we resort to the following technique, but I don't recommend it

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def created_at
    attributes['created_at'].strftime("%Y-%m-%d %H:%M")
  end
end
Hany Moh.
  • 949
  • 1
  • 11
  • 11