在导入到 12/1/2011 (mm / dd / yyyy)格式的MySQL时,不确定如何更改csv文件中的日期。 MySQL是yyyy / mm / dd。
我该怎么做?
我的佣金文件
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",
... ^
答案 0 :(得分:3)
if row[7].present?
date = row[7].split("/")
new_date = "#{date[2]}/#{date[0]}/#{date[1]}"
else
new_date = "N/A"
end
修改强> 你得到的错误是因为行是零。我添加了一张零支票。
答案 1 :(得分:2)
如果您需要验证日期,则可以使用DateTime::strptime
和DateTime#strftime
方法:
require 'date'
# ... snip ...
:clientdate => DateTime.strptime(row[7], "%m/%d/%Y").strftime("%Y/%m/%d")