Question

In PostgreSQL, I need a way to determine if the current time is within the hours of operation of a certain model with an opens_at and closes_at timestamp. What would be a valid Postgres way of doing this.

For Sqlite3 I had:

                        (opens_at > closes_at AND
                        (TIME(opens_at) > :now OR :now < TIME(closes_at)))
                        OR
                        (closes_at > opens_at AND
                        (TIME(opens_at) < :now AND TIME(closes_at) > :now))

I forgot to mention this is running through ActiveRecord so :now is actually equal to the current UTC time.

Was it helpful?

Solution

Probably the easiest thing to do is to cast the timestamps to times and use localtime:

opens_at::time > localtime or localtime < closes_at::time
...

Rails will have everything in UTC inside the database (including the database connection) so you don't have to worry about time zone issues.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top