Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing times only, without dates?

I need to write a method that will check if Time.now is in between the open hours and the close hours of a shop.

The open and close hours are saved as a Time object but I can't compare it corectly because the shop saved its hours at 2012/2/2 so the open hours will be something like:

2012-02-02 02:30:00 UTC

and Time.now will be:

07:23 +0200

How can I compare just the time part without the date part?

like image 527
user1666543 Avatar asked Jan 15 '13 00:01

user1666543


People also ask

How do I compare dates in Excel without time?

Often you may want to compare two dates in Excel while ignoring the time values associated with the dates. Fortunately you can use the INT() function in Excel to extract just the date from a datetime value, which allows you to easily compare dates while ignoring the time.

How do you compare only the date with moments?

We can use the isAfter method to check if one date is after another. We create a moment object with a date string. Then we call isAfter on it with another date string and the unit to compare. Therefore isAfter is false since we compare the year only.


3 Answers

You can compare the Time without a date part, for example, as follows:

time1.utc.strftime( "%H%M%S%N" ) <= time2.utc.strftime( "%H%M%S%N" ) 
like image 64
Малъ Скрылевъ Avatar answered Sep 27 '22 18:09

Малъ Скрылевъ


There is a nice library https://github.com/bokmann/business_time which will do this and more for you.

BusinessTime::Config.with(beginning_of_workday: "8:30 am", end_of_workday: "5:30 pm") do
  Time.now.during_business_hours?
end

It will do much more for you, like rolling a time to next or previous opening time, counting business hours between two timestamps, etc.

like image 27
rewritten Avatar answered Sep 27 '22 17:09

rewritten


You can compare only time in rails without date part like:--- Here post_review is table and we are getting only these record of post_review which are created_at between 10 am ---5pm in any date

post_review.where("(created_at::time >= :start_time) AND (created_at::time <= :end_time)", 
    start_time: Time.parse("10 am").strftime("%r"),
    end_time:   Time.parse("5 pm").strftime("%r")
 )
like image 36
Ganesh Shrivas Avatar answered Sep 27 '22 18:09

Ganesh Shrivas