Ruby DateTime parsing format 'mm / dd / yyyy'

I am using ruby 1.9.3 and want to get a Date or Time object with ' mm/dd/yyyy ' date format string

 Time.zone.parse("12/22/2011") 

this gives me *** ArgumentError Exception: argument out of range

+45
ruby ruby-on-rails-3
Oct 28 '13 at 19:28
source share
4 answers
 require 'Date' my_date = Date.strptime("12/22/2011", "%m/%d/%Y") 
+80
Oct 28 '13 at 19:34 on
source share

As above, use the strptime method, but note the differences below

 Date.strptime("12/22/2011", "%m/%d/%Y") => Thu, 22 Dec 2011 DateTime.strptime("12/22/2011", "%m/%d/%Y") => Thu, 22 Dec 2011 00:00:00 +0000 Time.strptime("12/22/2011", "%m/%d/%Y") => 2011-12-22 00:00:00 +0000 

(+0000 is the time zone information, and I'm now in GMT - hence +0000. Last week, before the clock returned, I was in BST +0100. My application.rb contains the line config.time_zone = 'London' )

+10
Oct 28 '13 at 9:23
source share

Try Time.strptime("12/22/2011", "%m/%d/%Y")

+6
Oct 28 '13 at 19:31
source share

Is it possible to use Time.strptime("01/28/2012", "%m/%d/%Y") instead of Time.parse? This way, you better control how Ruby will parse the date.

If not, there are gems (e.g. ruby-american_date) to make Ruby 1.9 Time.parse behave like Ruby 1.8.7, but use it only if absolutely necessary.

 1.9.3-p0 :002 > Time.parse '01/28/2012' ArgumentError: argument out of range 1.9.3-p0 :003 > require 'american_date' 1.9.3-p0 :004 > Time.parse '01/28/2012' => 2012-01-28 00:00:00 +0000 
+5
Oct 28 '13 at 19:37
source share



All Articles