2011-07-22 352 views

回答

2

使用下面的代码

datetime.strftime("%I:%M %P") 
3

你从日期时间时如果你只是想要一个字符串输出,你可以这样做亚太区首席技术官Matt Chris用strftime表示,但是如果你想从的实例中获得Time的实例,你可以做到以下几点:

Time.parse(DateTime.now.to_s) 

如果你想解析字符串像"1/10/2011 9:00:00",并得到Time实例回来,你可以用同样的方法parse

Time.parse("1/10/2011 9:00:00") #=> 2011-10-01 09:00:00 -0500 

注意格式:Ruby在解析日期时使用非美国友好的d/m/y格式。

要从Time实例中输出时间的字符串表示形式,则返回strftime

希望这可以解决问题。

+0

这将是冷静,如果你能理想地提取只是一个时间对象,而不关联日期。 – Trip

+1

@Trip虽然时间不是一天的开始,但这是一个时间点。我同意一个“时间”概念与时间接口将是有益的。 – coreyward

+0

@Trip其实,这里有一个图书馆似乎这样做(我没有玩过它,只是检查了自述文件):https://github.com/JackC/tod – coreyward

4

如果您需要在时间搜索从日期时间

:conditions => ["created_at::time > ?", "08:30" ] 
17
DateTime.new(2011,10,1,9).to_s(:time) #=> "09:00" 

DateTime.now.to_s(:time) #=> "11:58" 

Time docs

0

随着翻译

如果你使用的I18n,你可以很容易地定义你的own time formats

本地化您将Time对象传递给I18n.l的时间格式或(最好)使用Rails的#l帮助程序。您可以通过将选择一个格式:格式选项

# app/views/home/index.html.erb 
<h1><%=t :hello_world %></h1> 
<p><%= flash[:notice] %></p 
<p><%= l Time.now, format: :short %></p> 

# config/locales/pirate.yml 
pirate: 
    time: 
    formats: 
     short: "arrrround %H'ish" 

参考@克里斯巴雷托的答案的格式选项列表