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?
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With