ruby DateTime parsing from 'mm/dd/yyyy' format

RubyRuby on-Rails-3

Ruby Problem Overview


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

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

this is giving me *** ArgumentError Exception: argument out of range

Ruby Solutions


Solution 1 - Ruby

require 'Date'
my_date = Date.strptime("12/22/2011", "%m/%d/%Y")

Solution 2 - Ruby

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 

(the +0000 is the timezone info, and I'm now in GMT - hence +0000. Last week, before the clocks went back, I was in BST +0100. My application.rb contains the line config.time_zone = 'London')

Solution 3 - Ruby

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

Solution 4 - Ruby

Would it be an option for you to use Time.strptime("01/28/2012", "%m/%d/%Y") in place of Time.parse? That way you have better control over how Ruby is going to parse the date.

If not there are gems: (e.g. ruby-american_date) to make the Ruby 1.9 Time.parse behave like Ruby 1.8.7, but only use it if it's 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 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTKumar StplView Question on Stackoverflow
Solution 1 - RubyhirolauView Answer on Stackoverflow
Solution 2 - RubyMitchView Answer on Stackoverflow
Solution 3 - RubyLachezarView Answer on Stackoverflow
Solution 4 - RubyLHHView Answer on Stackoverflow