Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new DateTime object in a specific time zone (preferably the default time zone of my app, not UTC)?

I have set the time zone in /config/application.rb, and I expect all times generated in my app to be in this time zone by default, yet when I create a new DateTime object (using .new), it creates it in GMT. How can I get it to be in my app's time zone?

/config/application.rb

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

irb

irb> DateTime.now => Wed, 11 Jul 2012 19:04:56 -0700   irb> mydate = DateTime.new(2012, 07, 11, 20, 10, 0) => Wed, 11 Jul 2012 20:10:00 +0000                    # GMT, but I want PDT 

Using in_time_zone doesn't work because that just converts the GMT time to PDT time, which is the wrong time:

irb> mydate.in_time_zone('Pacific Time (US & Canada)') => Wed, 11 Jul 2012 13:10:00 PDT -07:00               # wrong time (I want 20:10) 
like image 702
user664833 Avatar asked Jul 12 '12 02:07

user664833


People also ask

How do I set the timezone in DateTime?

Timezone aware object using datetime now(). time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.

How do you create a DateTime object in Ruby?

A DateTime object is created with DateTime::new , DateTime::jd , DateTime::ordinal , DateTime::commercial , DateTime::parse , DateTime::strptime , DateTime::now , Time#to_datetime , etc. require 'date' DateTime. new(2001,2,3,4,5,6) #=> #<DateTime: 2001-02-03T04:05:06+00:00 ...>


2 Answers

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  
like image 194
Peter Brown Avatar answered Sep 28 '22 05:09

Peter Brown


Another way without string parsing:

irb> Time.zone.local(2012, 7, 11, 21) => Wed, 07 Nov 2012 21:00:00 PDT -07:00 
like image 35
hangsu Avatar answered Sep 28 '22 06:09

hangsu