Derek
Derek

Reputation: 12398

Adding datetime timezone in Rails?

I'm using Rails 4, and Ruby 2.

How do you add a timezone to a DateTime? I want to add the PST timezone to a new DateTime.

I've tried:

d = DateTime.strptime('12/21/2012', '%m/%d/%Y')
 => 2012-12-21T00:00:00+00:00 
d.in_time_zone("Pacific Time (US & Canada)")
 => Thu, 20 Dec 2012 16:00:00 PST -08:00 

How do I get Fri, 21 Dec 2012 00:00:00 PST -08:00?

Upvotes: 2

Views: 118

Answers (1)

sites
sites

Reputation: 21815

Try:

d = DateTime.strptime('12/21/2012', '%m/%d/%Y').to_time - Time.now.utc_offset

If you are using Rails, remember to use Time.zone or DateTime.zone if it exists. From what I have read, when you use the XX.zone variation you get the config from the Rails app, while if you use it without zone you get the Ruby config, which I think is the system config.

Upvotes: 2

Related Questions