我一直在尝试根据一天中的时间输出Morning或。Afternoon我把时间变成了字符串,并尝试与它进行比较。这是我所拥有的:
t = Time.now
# => 2016-05-11 07:18:10 -0500
if t.to_s >= '12:00'
'Good afternoon'
else
'Good morning'
end
# => "Good afternoon"
Run Code Online (Sandbox Code Playgroud)
它默认为"Good afternoon". 为什么是这样?是因为 Ruby 将时间设置为 24 小时制吗?或者是编码中的某些内容?
您不需要任何字符串操作:
t = Time.now
# => 2016-05-11 20:26:11 +0800
t.hour
# => 20
Run Code Online (Sandbox Code Playgroud)
只需将其hour(整数)与进行比较即可12。