How to create a new DateTime object in a specific time zone (preferably the default time zone of my app, not UTC)?
You can use ActiveSupport's TimeWithZone (Time.zone
) object to create and parse dates in the time zone of your application:
1.9.3p0 :001 > Time.zone.now
=> Wed, 11 Jul 2012 19:47:03 PDT -07:00
1.9.3p0 :002 > Time.zone.parse('2012-07-11 21:00')
=> Wed, 11 Jul 2012 21:00:00 PDT -07:00
Another way without string parsing:
irb> Time.zone.local(2012, 7, 11, 21)
=> Wed, 07 Nov 2012 21:00:00 PDT -07:00
If I have it, I usually just specify the utc_offset when instantiating Time.new or DateTime.new.
[1] pry(main)> Time.new(2013,01,06, 11, 25, 00) #no specified utc_offset defaults to system time
=> 2013-01-06 11:25:00 -0500
[2] pry(main)> Time.new(2013,01,06, 11, 25, 00, "+00:00") #UTC
=> 2013-01-06 11:25:00 +0000
[3] pry(main)> Time.new(2013,01,06, 11, 25, 00, "-08:00") #PST
=> 2013-01-06 11:25:00 -0800