AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

How to convert postgres UTC into another timezone?

Is there a way to convert postgres UTC time to the user's timezone or at the very least Eastern Standard Time (I'd be grateful with either answer)?

I thought that there was a way to change postgres UTC time, but I don't think there is without causing a lot of issues. From what I read it would be better to use code on the frontend that would convert it to the correct time zone?

This barely makes sense to me.

What's the point?

So that when a user checks off he completed a good habit, the habit disappears, and is suppose to reshow tomorrow at 12am, but the habits end up reshowing later in the day because of UTC.

habit.rb

scope :incomplete, -> {where("completed_at is null OR completed_at < ?", Date.today)} # aka those habits not completed today will be shown

def completed=(boolean)
  self.completed_at = boolean ? Time.current : nil
end

def completed
  completed_at && completed_at >= Time.current.beginning_of_day
end

Upvotes: 0

Views: 218

Answers (2)

Athar
Athar

Reputation: 3268

please change your scope to this, it will search time zone specifically.

scope :incomplete, -> {where("completed_at is null OR completed_at < ?", Time.zone.now.beginning_of_day)}

Upvotes: 1

adamliesko
adamliesko

Reputation: 1915

Place this code snippet into your application.rb

  config.time_zone = 'Eastern Time (US & Canada)'

and run this so it will be set on heroku heroku config:add TZ=America/Los_Angeles.

Generally, you can also use #in_time_zone. Always use the time like Time.zone.now.

Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
DateTime.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
Date.new(2000).in_time_zone('Alaska')  # => Sat, 01 Jan 2000 00:00:00 AKST -09:00

date and time zones

api docs

Upvotes: 0

Related Questions