How to change created_at format
Asked Answered
C

4

17

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?

Catnip answered 12/4, 2015 at 12:31 Comment(0)
T
39

You can read more about strftime here

t.created_at.strftime("%Y-%m-%d")
Trickery answered 12/4, 2015 at 12:39 Comment(0)
B
16

And it can be done even easier way:

t.created_at.to_date
Bullwhip answered 13/8, 2016 at 13:50 Comment(1)
sorry for asking simple questions, but : where do you put that ? in application_controller ?Melon
M
2

Or with locales:

// view:
<% @articles.each do |c| %>
    <%= l c.created_at.to_date, format: :short %>
<% end %>
Melon answered 25/5, 2019 at 16:3 Comment(0)
H
2

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
Hectogram answered 3/9, 2020 at 5:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.