简体   繁体   中英

CSV date format to MySQL date format

When I try to import my CSV file to MySQL, all the date become 0000-00-00 .

CSV date format is DD/MM/YYYY like this 16/11/2016.

MySQL format is: YYYY/MM/DD . I am using phpmyadmin to import this. How to solve this date transfer?

I think, you need to change the date format before adding to MYSQL database.

$old_date = date('dd/mm/yyyy');            
$middle = strtotime($old_date);            
$new_date = date('yyyy/mm/dd', $middle);   

The format DD/MM/YYYY is not a valid date in MySQL. You could use LOAD DATA along with STR_TO_DATE to parse the date strings into actual dates which MySQL can recognize:

LOAD DATA INFILE 'path/to/file.csv'
INTO TABLE yourTable FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' 
(
    col1, col2, @var1, col4
)
SET date_col = STR_TO_DATE(@var1, '%d/%m/%Y')

The above assumes that your table has 4 columns, and that the third column you are reading in from your CSV file is the troublesome date. The trick here is that each date string will get mapped on the fly into a valid date type, leaving you with the result you want.

Another option is to use the CSV Lint plug-in for Notepad++. The plug-in can detect the data types found in the csv file, including the datetime formats. You can just select Reformat to change all DD/MM/YYYY values to YYYY/MM/DD format.

Or, instead of using LOAD DATA INFILE there's also a menu option to convert the csv file to an SQL insert script.

CSV Lint 插件

It will create INSERT statements for each line in the csv file, in batches of 1000 records. Plus it takes into account the column datatypes and datetime formats, and it will automatically convert the date values to the correct SQL date time.

CSV Lint 插件生成 SQL 插入

The generated SQL script also contains a CREATE TABLE part with the correct data type for each column.

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