Rails: How to parse date-time string into a specific time zone

前端 未结 7 1224
天命终不由人
天命终不由人 2020-12-01 10:23

I\'m using Rails 3.2 and ruby 1.9.3 on Debian. I have an app that collects a date, time, and timezone in the form of strings via an HTML form. Something like this:



        
7条回答
  •  温柔的废话
    2020-12-01 10:55

    This is the method that I came up with. Not the prettiest, but it works. Allows parsing the string using a specified format, and then turning it into the format that I know Time.zone.parse requires.

    class ActiveSupport::TimeZone
      def strptime(time, format='%m/%d/%Y')
        formatted = Time.strptime(time, format).strftime('%Y-%m-%d %T')
        parse(formatted)
      end
    end
    

    Then you can do something like what was mentioned in another question, but with a specified format:

    zone = "Central Time (US & Canada)"  
    ActiveSupport::TimeZone[zone].strptime('2013-04-03', '%Y-%m-%d')
    

    Or if you already have a time zone set:

    Time.zone = "Central Time (US & Canada)" 
    Time.zone.strptime('01/13/2006')
    

    I used a default format of %m/%d/%Y because that's what my user input is most of the time. You can customize this to your needs, or use the default format DateTime uses which is believe is iso8601 (%FT%T%z)

提交回复
热议问题