LearningROR LearningROR - 1 year ago 46
Ruby Question

check current time is greater than defined time rails 4

I would like to check it my current time is greater than a defined time.

My start time could be anytime from day:


Time.now.strftime("%I:%M %p")
"11:17 AM"

I need to see if this time is greater than
"04:00 PM"
of same day

Means if any point my
current time
is greater than same day of
04:00 PM

I have tried:

<%= distance_of_time_in_words(Time.now.strftime("%I:%M %p"), "04:00:00 PM") %>

but its not working as expected.

any possible way to get this?

Plus please could anyone tell best practices as well to calculate the difference?

Answer Source

You can use beginning_of_day and then manoeuvre to the target time by adding hours.

If Time.now > Time.now.beginning_of_day + 16.hours

The fact that Time.now includes a date component doesn't matter, since it's the same date on both sides of the comparison.