Reputation: 19969
I have a rails app that has the time zone set in application.rb with:
config.time_zone = 'Pacific Time (US & Canada)'
I'd like to save a time as:
day, hour=25, 10
....
params[:order][:pickup_at] = DateTime.new(2015,11,day,hour,00,00)
and thought it would write as
2015-11-25 18:00:00
into our table which is a Postgres 9.4 instance and the pickup_at is a timestamp without time zone.
Instead it is:
2015-11-25 10:00:00
doing:
params[:order][:pickup_at] =DateTime.new(2015,11,25,10,00,00).in_time_zone("Pacific Time (US & Canada)")
doessn't fix. It seems what I'm trying to do is very simple. Into a timestamp adjust for what we have our current timezone set as and adjust accordingly.
How would I make this work?
Upvotes: 0
Views: 552
Reputation: 621
DateTime has a default offset of 0, meaning it provides you a DateTime object in UTC ("non-timezone'd" as you put it) by default:
http://ruby-doc.org/stdlib-2.2.3/libdoc/date/rdoc/DateTime.html#method-c-new
If the UTC time you want to specify is 2015-11-25 18:00:00
, you should write:
day, hour=25, 10
....
params[:order][:pickup_at] = DateTime.new(2015,11,day,hour,00,00,'-8')
That last -8
argument is the offset, which tells DateTime that your time zone is in PST.
DateTime.new(2015,11,day,hour,00,00,'-8').utc
then yields:
Wed, 25 Nov 2015 18:00:00 +0000
If you wanted to make this dynamic against your application's Time zone, you could write:
day, hour = 25, 10
# Take application timezone offset in seconds and convert it to hours
hour_offset = Time.zone.utc_offset / 60 / 60
params[:order][:pickup_at] = DateTime.new(2015,11,day,hour,00,00, hour_offset.to_s).utc
Upvotes: 0