簡體   English   中英

將Rails CSV導入的日期格式更改為MYSQL

[英]Changing Date Format on Rails CSV Import to MYSQL

不確定以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", 
...                               ^
   if row[7].present?
      date = row[7].split("/")
      new_date = "#{date[2]}/#{date[0]}/#{date[1]}"
   else
     new_date = "N/A"
   end

編輯:您得到的錯誤是因為該行為nil。 我加了一張零支票。

如果需要驗證日期,則可以使用DateTime::strptimeDateTime#strftime方法:

require 'date'

# ... snip ...
:clientdate => DateTime.strptime(row[7], "%m/%d/%Y").strftime("%Y/%m/%d")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM