How to create a Ruby DateTime from existing Time.zone for Rails? How to create a Ruby DateTime from existing Time.zone for Rails? ruby ruby

How to create a Ruby DateTime from existing Time.zone for Rails?


Try:

Time.zone = "Pacific Time (US & Canada)"Time.zone.parse('8-11-2013 23:59:59') #=> Fri, 08 Nov 2013 23:59:59 PST -08:00 

OR

Time.now.in_time_zone("Pacific Time (US & Canada)")

OR

DateTime.now.in_time_zone("Pacific Time (US & Canada)")


You can use Time.zone.local if you set Time.zone previously:

user_time = Time.zone.local(params[:year].to_i, params[:month].to_i, params[:day].to_i, params[:hour].to_i, params[:minute].to_i, 0)

Have a look at the ActiveSupport::TimeWithZone documentation.


You can use the following code to create a DateTime object with your desired TimeZone.

DateTime.new(2013, 6, 29, 10, 15, 30).change(:offset => "+0530")

UPDATE: With new 1.9.1 version of Rails Ruby, the below line does the same job like a magic.

DateTime.new(2013, 6, 29, 10, 15, 30, "+0530")

Documentation here