2

在导入2011年 12 月 1 日(mm/dd/yyyy)格式的 MySQL 时,不确定如何更改 csv 文件中的日期。MySQL 在 yyyy/mm/dd 中。

我怎样才能做到这一点?

我的 rake 文件

require 'csv'
require 'date'

desc "Import gac from csv file"
task :import => [:environment] do
  Dir.chdir("#{Rails.root}/lib/assets")
  csv_file = "file.csv" 
  CSV.foreach(csv_file, :headers => true) do |row|
    Institution.create({
      :company => row[0],
      :solveid => row[2],
      :phone => row[5],
      :other => row[6],
      :clientdate => (DateTime.strptime row[7], "%m/%d/%Y").strftime "%Y/%m/%d", 
      :cunumber => row[1],
      :street => row[8], 
      :city => row[9], 
      :state_id => row[4], 
      :zip => row[10],
      :source => row[11], 
      :source2 => row[12],
      :demodate1 => (DateTime.strptime row[13], "%m/%d/%Y").strftime "%Y/%m/%d",
      :demodate2 => (DateTime.strptime row[14], "%m/%d/%Y").strftime "%Y/%m/%d",
      :demodate3 => (DateTime.strptime row[15], "%m/%d/%Y").strftime "%Y/%m/%d",
      :client => row[17],
      :prospect => row[19], 
      :alliedlead => row[16], 
      :notcontacted => row[18]
    })
  end
end

这给了我一个错误。

rake import
rake aborted!
/Users/dave/rails_projects/allied_contest/lib/tasks/intitutions.rake:14: syntax error, unexpected tSTRING_BEG, expecting '}'
... row[7], "%m/%d/%Y").strftime "%Y/%m/%d", 
...                               ^
/Users/dave/rails_projects/allied_contest/lib/tasks/intitutions.rake:14: syntax error, unexpected ',', expecting keyword_end
...%m/%d/%Y").strftime "%Y/%m/%d", 
...                               ^
4

2 回答 2

3
   if row[7].present?
      date = row[7].split("/")
      new_date = "#{date[2]}/#{date[0]}/#{date[1]}"
   else
     new_date = "N/A"
   end

编辑: 您得到的错误是因为该行为零。我添加了一个零支票。

于 2012-11-02T03:32:03.130 回答
2

如果您需要验证日期,则可以使用DateTime::strptimeandDateTime#strftime方法:

require 'date'

# ... snip ...
:clientdate => DateTime.strptime(row[7], "%m/%d/%Y").strftime("%Y/%m/%d")
于 2012-11-02T03:35:37.660 回答