开发者

Change format of created_at in Rails 3.1?

开发者 https://www.devze.com 2023-04-04 03:46 出处:网络
I am calling the date a record was created at in a basic app running Rails 3.1. <%= @issue.created_at %>

I am calling the date a record was created at in a basic app running Rails 3.1.

<%= @issue.created_at %>

The above outputs the following timestamp:

2011-09-10 14:44:24 UTC

What is the simplest way of altering the way this displays? I would like something like this:

10 Sept. 2011

and then somehow call it again with a different format:

14:44

so I can call it twice and merge the two together:

10 Sept. 2011
14:44

The reason I want to call it twice rather than create a helper to format a two line date/time is to allow me to call the date in some places and just the time in oth开发者_Go百科ers.


The simplest thing to do is to use the strftime function

# Day / Month / Year
@issue.created_at.strftime("%d %b. %Y")
# Hour:Min
@issue.created_at.strftime("%H:%M")

You could put those two calls in separate helpers if you find yourself doing it a lot.


I would use I18n. Take a look at some example http://guides.rubyonrails.org/i18n.html#adding-date-time-formats. It's a clean and flexible way of formatting dates and times.


<%= l(@issue.created_at, :format=>:your_format) %>

in locale YAML (app/config/locale/country_id.yml) you must declare

time:
 formats:
  your_format: '%d %b. %Y'
  your_another_format: '%I:%M'

Date formatting should be declared inside your i18n YAML definition file for easy configure, and other date format could be found here


Check out http://www.foragoodstrftime.com/ for an easy way to customize date/time formatting @spike


You can do:

@issue.created_at.to_date.iso8601


to_s also takes format input argument:

http://apidock.com/rails/ActiveSupport/TimeWithZone/to_s

0

精彩评论

暂无评论...
验证码 换一张
取 消