lundi 30 mai 2016

How to compare Hour and minute in Ruby for Time datatype

I am writing code to determine when to show site announcement for our site. Admin are allowed to set start_time and finish_time to display site announcement. Announcement should only be displayed between those times. Admin can select different time for weekdays and different time for weekends.

The way I am checking now is something like this:

time = Time.now
current_hour = time.strftime('%I').to_i
current_minute = time.min

announcement_start_hour = start_time.strftime('%I').to_i
announcement_start_minute = start_time.min

announcement_finish_hour = finish_time.strtfime('%I').to_i
announcement_finish_minute = finish_time.min

then i have logic something like this

if (current_hour >= announcement_start_hour && current_hour <= announcement_finish_hour) &&(announcement_start_minute >= current_minute && current_minute < announcement_finish_minute)

  // show announcement

else

  // don't show announcement

But the problem that I am encountering is let's say our current time is 1 pm and our announcement is supposed to be displayed form 11 am until 11 pm

So,

curernt_hour = 1
current_mintue = 00

announcement_start_hour = 11
announcement_start_minute = 00

announcement_finish_hour = 11
announcemnt_finish_minute = 00

so current_hour >= announcement_start_hour will be false because ( 1 is < 11) but in reality 1 is 1 pm which is 13 in 24 hr time.

There needs be better way to compare hour and minutes for Time in Ruby. I will encounter similar problem even when i use 24 hr format for time.

NOTE: data type for both start_time and finish_time is Time not DateTime

Aucun commentaire:

Enregistrer un commentaire