2012-04-27 28 views
2

我正在使用Ruby on Rails v3.2.2,我想显示一个类似<day_number> <month_name> <year_number>的数据。也就是说,我有一个datetime数据库表列,并且我想将其包含的值更改为例如2012-04-27 00:00:0027 april 2012如何处理`datetime`值以便将它从“2012-04-27 00:00:00”更改为“2012年4月27日”?

我该如何做到这一点?

+0

犯错,你为什么不只是把它保存为一个'date'而不是'datetime'? – 2012-04-27 15:19:35

+0

@安德鲁马歇尔 - 这是因为我想尽可能精确。 ;-) – Backo 2012-04-27 15:22:33

回答

5

标准方式是使用导轨本地化。

模型

I18n.l(datetime, :format => :short) 

控制器

I18n.l(datetime, :format => :long) 

视图

<%= l(datetime), :format => :custom %> 

配置/语言环境/ en.yml

en: 
    time: 
    formats: 
     long: "%A %B %d %Y | %I:%M %p GMT" 
     short: "%d %B %Y, %H:%M GMT" 
     custom: "your custom format" 
    date: 
    formats: 
     short: "%d %B %Y" 
     long: "%A %B %d %Y" 
     custom: "your custom format" 

在你的情况下,格式应该是“%d%A%Y”。

好处是,如果你想改变格式,你可以在一个地方为你正在使用的所有日期时间做到这一点。

+0

从技术上讲,如何“命名”所有这些'%A%B%d%Y ...',以及在哪里可以找到一些关于如何选择我需要的最佳格式的文档? – Backo 2012-04-27 13:34:39

+0

试试这个http://snippets.dzone.com/posts/show/2255或http://apidock.com/ruby/DateTime/strftime或尝试谷歌与关键字[strftime红宝石] :) – Suborx 2012-04-27 13:38:13

1

您可以使用该方法

str_name.strftime("%d %A %Y") 
相关问题