Ruby-on-rails 在 Rails 3.1 中更改 created_at 的格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7372574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change format of created_at in Rails 3.1?
提问by dannymcc
I am calling the date a record was created at in a basic app running Rails 3.1.
我称在运行 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 others.
我想调用它两次而不是创建一个帮助程序来格式化两行日期/时间的原因是允许我在某些地方调用日期而在其他地方调用时间。
采纳答案by lucapette
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.
我会使用 I18n。看看一些示例http://guides.rubyonrails.org/i18n.html#adding-date-time-formats。这是格式化日期和时间的一种简洁灵活的方式。
回答by spike
The simplest thing to do is to use the strftime function
最简单的做法是使用 strftime 函数
# 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.
如果您发现自己经常这样做,您可以将这两个调用放在单独的助手中。
回答by Agung Prasetyo
<%= l(@issue.created_at, :format=>:your_format) %>
in locale YAML (app/config/locale/country_id.yml) you must declare
在语言环境 YAML (app/config/locale/country_id.yml) 中,您必须声明
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
日期格式应该在你的 i18n YAML 定义文件中声明以便于配置,其他日期格式可以在这里找到
回答by akeyva
Check out http://www.foragoodstrftime.com/for an easy way to customize date/time formatting @spike
查看http://www.foragoodstrftime.com/以轻松自定义日期/时间格式@spike
回答by flyer88
You can do:
你可以做:
@issue.created_at.to_date.iso8601
@issue.created_at.to_date.iso8601
回答by Daniel Korenblum
to_s also takes format input argument:
to_s 还采用格式输入参数:

