Search code examples
ruby-on-railstimestrptime

How to strptime a time string as a different from local time zone


When I use Time.strptime in my local computer, I got like this:

ENV['LC_CTYPE']
=>"ja_JP.UTF-8"
Time.strptime("10/12/2015-4:05pm", '%m/%d/%Y-%I:%M%p')
=> 2015-10-12 16:05:00 +0900

How can I parse the string as a different time zone like 'Central Time (US & Canada)'?

I tried with Time.zone = 'Central Time (US & Canada)', but the result was same.

I want to use the function in Rails environment so it's ok to use active_support.


Solution

  • %Z is how you represent timezone in date/time format. Try the following:

    time_zone = 'Central Time (US & Canada)'
    DateTime.strptime "10/12/2015-4:05pm #{time_zone}", '%m/%d/%Y-%I:%M%p %Z'