Wednesday, June 24, 2015

How to convert date in string to date in date datatype in PHP

I was working on a Web portal, where there was a use case to import the csv or xls to a MySql database. In the database there was a field for date with the date data type. And from the xls or csv when we are importing , it imports as the string.  So when you are trying to insert a string or text in date data type, it adds as ‘0000-00-00’ which is wrong.

For that, to insert it correctly we need to convert the date string to date format before inserting.

Consider the below csv file to be imported.  Dob (Date of Birth) is the column that contains the date.

First row is the header. Now the content of the DOB, DOJ and Anniversary columns has to be converted to date format.  Below is the code to be considered to convert it.

          //For DOB
              $time = strtotime($data[7]);
              $data[7] = date('Y-m-d',$time);

// For DOJ
             $time = strtotime($data[8]);
             $data[8] = date('Y-m-d',$time);
         //For Anniversary
           $time = strtotime($data[11]);
           $data[11] = date('Y-m-d',$time);

strtotime(string)’ is the function that converts the string to time format. Now this has to be converted to required date format. That can be done using date(format, time) function.
Format you can use the required format. Here I am using yyyy-mm-dd format for that we can use ‘Y-m-d’. Now the $date[7], $date[8] and $date[11] contains the date in date datatype and also in yyyy-mm-dd format.

That’s it . Happy Coding

No comments: