简体   繁体   中英

Date conversion in rails

I am importing data from CSV inside Rails 3.2 and saving it to mongodb collection and everything works fine except the date field. The imported date format is DD/MM/YYY. Please how can I convert the imported date to YYYY-MM-DD?

Thanks

You could use date parsing like this:

Date.strptime('01/02/2003', '%d/%m/%Y').to_s    #=> "2003-02-01"
  • Date.strptime creates a Date object from a string in the given format

  • Date#to_s returns it in the ISO 8601 format (ie YYYY-MM-DD)

But it depends on how big your CSV is - this would create a bunch of intermediate Date objects which would be a bit slower than a (slightly ugly) string indexing approach:

def reformat_date(date)
  "#{date[6..9]}-#{date[3..4]}-#{date[0..1]}"
end

reformat_date('01/02/2003')     #=> "2003-02-01"

Update

I was curious so I ran some quick benchmarks - the date parsing method was about 2.7 times slower than the string method (5.289s vs 1.981s for a million conversions, Ruby 1.9.3/Windows). YMMV.

You may need

require 'date'

Then use the following statement to parse the date:

d = Date.strptime('09/10/2012', '%d/%m/%Y')

Using the following examples will return the right format:

d.year #=> 2012
d.mon  #=> 10
d.day  #=> 9
d.strftime('%Y/%m/%d')  #=> "2012/10/09"

Then save it to the database. I'm not familiar with mongodb, though, but I'm sure you know what to do.

For more information on date parsing you should visit http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/DateTime.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM