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

55,599

Solution 1

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)")

Solution 2

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

Solution 3

DateTime.new accepts optional offset argument (as the seventh) starting from ruby 1.9.1

We can write

DateTime.new(2018, 1, 1, 0, 0, 0, Time.zone.formatted_offset)

Solution 4

If you have already a correct DateTime object with the name 'datetime', and you want to copy it, you can simply call the 'getutc' on it and after that use the 'in_time_zone'

DateTime.new(datetime.getutc.year, datetime.getutc.month, datetime.getutc.day, time.getutc.hour, time.getutc.min).in_time_zone
Share:
55,599
at.
Author by

at.

Updated on May 16, 2020

Comments

  • at.
    at. about 4 years

    I have users entering in dates in a Ruby on Rails website. I parse the dates into a DateTime object with something like:

    date = DateTime.new(params[:year].to_i, params[:month].to_i, params[:day].to_i, params[:hour].to_i, params[:minute].to_i)
    

    or

    date = DateTime.parse(params[:date])
    

    Both DateTimes will not be in the time zone of the user which I previously set with something like:

    Time.zone = "Pacific Time (US & Canada)"
    

    How do I parse the above DateTimes to be in the right time zone? I know the DateTime.new method has a 7th argument for the time offset. Is there an easy way to look up the offset for a time zone in a given time? Or should I be using something other than DateTime?