mercredi 8 février 2017

Query datetime as text and include different timezones

Short version: I have 2 users in DB, each created in a different timezone:

User.find(1).created_at
=> Thu, 04 Aug 2016 11:15:29 IDT +03:00
User.find(33).created_at
=> Sun, 01 Jan 2017 17:50:20 IST +02:00

So my table shows 11:15, and 17:50. so for example I would like to search for 17:50, and later 11:15 as text.

No problem I'll just convert the date to text, then search it, But user won't be found, since the it's saved as UTC:

User.where("to_char(created_at,'DD-Mon-YYYY HH24:MI:SS') ilike ?", '%17:50%').first
=> nil

To find it I'll just apply the offset to my query (adding time zone UTC+2), and indeed user was found:

User.where("to_char(created_at AT TIME ZONE 'UTC+2','DD-Mon-YYYY HH24:MI:SS') ilike ?", '%17:50%').first
=> User #33 @2017-01-01 17:50:20 +0200

BUT some users are saved as UTC+3 and some as UTC+2.. I can't apply both offsets...

  • When I use UTC+2 I will only find users which were created as +2 (like User.find(33)).
  • When I use UTC+3 I will only find users which were created as +3 (like User.find(1)).

My question: How to do a where query- a text search for both users' created_at hour, as they were both saved in a different timezone offset?


More Details:

I notice in DB they are saved as UTC (I think):

User.select("created_at as created_at_db").find(1).created_at_db
=> "2017-01-01 15:50:20.903289"
User.select("created_at as created_at_db").find(1).created_at_db
=> "2016-08-04 08:15:29.171776"

Time setting:

#application.rb
    config.time_zone = 'Jerusalem'
    config.active_record.default_timezone = :utc

Aucun commentaire:

Enregistrer un commentaire