Question

I have a CSV file that I am importing into MySQL using PHP but the problem is that the timestamp is in the following format

01/02/2014 00:00:00

I have read about MySQL timestamp and it only accepts in the following format

01-02-2014 00:00:00 

from what I know. I am wondering if there is a way that I can convert the column which I have set as varchar into timestamp and convert it into a format that MySQL will accept ?

Is there an SQL query or a PHP function that I can use to do this? Also, the no of rows exceeds more than a million so I want it to be as fast as possible.

Any suggestions would be appreciated.

Was it helpful?

Solution

  1. If your MySQL column is DATE type:

$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));

  1. If your MySQL column is DATETIME type:

$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));

You haven't got to work strototime(), because it will not work with dash - separators, it will try to do a subtraction.

Update, the way your date is formatted you can't use strtotime(), use this code instead:

$date = '02/07/2009 00:07:00';
$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $date); 
echo $date;

Output:

2009-07-02 00:07:00

OTHER TIPS

You will see in the following link (Convert one date format into another in PHP) that One can use either DateTime or strtotime() with date() to create the new format.

I would use the DateTime:

<?php
$date = date_create_from_format('j-M-Y', '15-Feb-2009');
echo date_format($date, 'Y-m-d');
?>

This solution is given by the php documentation.(http://php.net/manual/en/datetime.createfromformat.php)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top