Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 904
mwilliams Avatar asked Feb 25 '10 21:02

mwilliams


2 Answers

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.

like image 147
TheClair Avatar answered Oct 11 '22 09:10

TheClair


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"
like image 27
Midwire Avatar answered Oct 11 '22 10:10

Midwire