Strptime with Timezone Strptime with Timezone ruby ruby

Strptime with Timezone


I use it the following way:

ruby-1.9.2-head :001 > require 'date' => true ruby-1.9.2-head :002 > fmt = "%m-%d-%Y %H:%M:%S %Z" => "%m-%d-%Y %H:%M:%S %Z" ruby-1.9.2-head :003 > DateTime.strptime "10-26-2011 10:16:29 CET", fmt => #<DateTime: 2011-10-26T10:16:29+01:00 (212186380589/86400,1/24,2299161)> ruby-1.9.2-head :004 > DateTime.strptime "10-26-2011 10:16:29 UTC", fmt => #<DateTime: 2011-10-26T10:16:29+00:00 (212186384189/86400,0/1,2299161)> ruby-1.9.2-head :005 > DateTime.strptime "10-26-2011 10:16:29 PST", fmt => #<DateTime: 2011-10-26T10:16:29-08:00 (212186412989/86400,-1/3,2299161)> 

Is it what you mean?


This works in Rails 5:

Time.zone.strptime("2017-05-20 18:20:10", "%Y-%m-%d %H:%M:%S")

Returns the time in the specified time zone.


At least as of Rails 4.2 (maybe earlier, haven't tested) as long as you use Time#strptime instead of DateTime.strptime, the current time zone is automatically applied:

> DateTime.strptime('12/28/2016 5:00 PM', '%m/%d/%Y %H:%M %p')=> Wed, 28 Dec 2016 17:00:00 +0000> Time.strptime('12/28/2016 5:00 PM', '%m/%d/%Y %H:%M %p')=> 2016-12-28 17:00:00 -0800