如何让时间早上或下午回归

时间:2016-05-11 12:19:25

标签: ruby time

我一直在尝试输出MorningAfternoon,具体取决于当天的时间。我把时间变成了一个字符串,并试图与它进行比较。这就是我所拥有的:

t = Time.now
# => 2016-05-11 07:18:10 -0500
if t.to_s >= '12:00'
  'Good afternoon'
else
  'Good morning'
end
# => "Good afternoon"

默认为"Good afternoon"。为什么是这样?是因为Ruby在24小时制定时间吗?或者它是编码内的东西?

3 个答案:

答案 0 :(得分:4)

您不需要任何字符串操作:

t = Time.now
# => 2016-05-11 20:26:11 +0800
t.hour
# => 20

只需将其hour(整数)与12进行比较。

答案 1 :(得分:3)

您正在比较字符串 - 这不会为您提供您期望的结果。

Time.now.to_s输出一个字符串,如:“2016-05-11 13:27:43 +0100”。将它与“12:00”进行比较时,它是字符串中字母的比较,而不是它们所代表的时间。

请改为尝试:

t = Time.now

if t.strftime('%P') == 'pm'
  'Good afternoon'
else
  'Good morning'
end

strftime的文档:http://ruby-doc.org/core-2.3.1/Time.html#method-i-strftime

答案 2 :(得分:1)

require 'time'

t = Time.new
puts "Good %s" % [(t.to_i/43199).even? ? "morning" : "afternoon"]
Good morning

t += 43199
puts "Good %s" % [(t.to_i/43199).even? ? "morning" : "afternoon"]
Good afternoon

注意:43199 = 12*60*60/2 - 1

只是说'。

相关问题