Neon_10
Neon_10

Reputation: 731

How to change created_at format

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?

Upvotes: 17

Views: 30428

Answers (4)

Hany Moh.
Hany Moh.

Reputation: 989

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

Upvotes: 3

thiebo
thiebo

Reputation: 1435

Or with locales:

// view:
<% @articles.each do |c| %>
    <%= l c.created_at.to_date, format: :short %>
<% end %>

Upvotes: 2

Tsvetkova Maria
Tsvetkova Maria

Reputation: 161

And it can be done even easier way:

t.created_at.to_date

Upvotes: 16

Mihail Petkov
Mihail Petkov

Reputation: 1545

You can read more about strftime here

t.created_at.strftime("%Y-%m-%d")

Upvotes: 39

Related Questions