Timezone independent due date comparison in rails scope

Consider the following case. I have a **Voucher** model with a datetime **activation\_due\_date** field and user model that has up-to-date information about his location (timezone, UTC offset).

I want to check if he requests voucher activation before due date in any of available time zones. For instance, If a due date is set to 28.08.2018 23:59 UTC I want my scope before\_activation\_due to check if he requests something before 28.08.2018 - 23:59 in his current time zone **so my due date is not something fixed** \- it depends on users location. In particular moment in time in one place it can be after due date and in the other before.

I have tried the following approach.


`scope :before_activation_due, lambda { |user|`

`where('activation_due_date > ? ', Time.current.to_utc + user.utc_offset)`


My questions are:

1. Is this a right approach? If not, what is the proper way for dealing with such cases?
2. How to test such a scope? The current timestamp is probably taken from a database server (I use postgres) when comparing datetimes during query execution so I am not sure how to mock it in my specs.

Thanks in advance.

Leave a Comment