13aal 13aal - 6 months ago 13
Ruby Question

How to make time return morning or afternoon

I've been attempting to output either

Morning
or
Afternoon
depending on the time of the day. I turned the time into a string, and tried to compare against it. Here's what I have:

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


It defaults to
"Good afternoon"
. Why is this? Is it because Ruby sets up time in a 24 hour clock? Or is it something within the coding?

Answer

You don't need any string manipulation:

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

Just compare its hour (an integer) with 12.