mwilliams
mwilliams

Reputation: 9978

Parsing dates to a Rails friendly format

I've got a batch of a 100k or so records that I'm importing to a Rails app.

There's a date in each row formatted like the following: 03/17/81

However, when I try to just assign it to a date field, it gets converted as follows:

ruby-1.8.7-p174 > "03/17/81".to_date
 => Sat, 17 Mar 0081 

Ultimately I would like the format to result in 1981-03-17

Would this best be done on the import or should I be overriding in my Rails config to set the date standard to the format I need and what's the right approach in Rails 2.3.5?

Upvotes: 9

Views: 8994

Answers (4)

TheClair
TheClair

Reputation: 721

Use

d = Date.strptime("03/17/81", "%m/%d/%y")

To get it out in 1981-03-17 use:

d.to_s

See Date Rubydoc.

Upvotes: 19

Midwire
Midwire

Reputation: 1100

The proper way to do this, if you are going to reuse the format in multiple places is to do something like this: http://seanbehan.com/ruby-on-rails/custom-date-formats-for-your-rails-application/

Create a file config/initializers/date_formats.rb

...containing this:

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
  :short_date => "%Y/%m/%d"
)

Then you should see:

ruby-1.8.7-p174 > date = "03/17/81".to_date
ruby-1.8.7-p174 > date.to_s(:short_date)
#=> "1981/03/17"

Upvotes: 3

Simone Carletti
Simone Carletti

Reputation: 176362

Don't change Rails, change your code. I don't see any problem in creating a method that converts the string into a suitable date.

string = "03/17/81"
date   = if string =~ %r{(\d+)/(\d+)/(\d+)}
  Date.parse("19#{$3}-#{$1}-#{$2}")
else
  nil # failover
end

Upvotes: 0

Ben
Ben

Reputation: 6967

Try Chronic (gem install chronic):

require 'rubygems'
require 'chronic'
puts Chronic.parse "03/17/81"
#=> Tue Mar 17 12:00:00 -0800 1981

Returns a Time object.

Upvotes: 1

Related Questions