5

I have the following problem. I have a string, which contains time and date as follows: dd/MM/yy hh:mm:ss This I have in PHP. And then I have a MySQL database, which has a column of a datetime format, where I need to insert this value. Obviously the problem is, that the format is different, so instead of the actual date, it results in a field "0000-00-00 00:00:00".

Could you please help me with converting this string and then inserting it properly into MySQL? For the MySQL I use the standard INSERT INTO command.

1
  • Sounds like you'll have to parse the string and build new date from the values you get? Doesn't look all that hard. Commented Sep 29, 2013 at 17:12

4 Answers 4

7

From the DATETIME documentation:

MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format.

I'd use PHP's DateTime class and DateTime::createFromFormat() method, and convert the data into a MySQL-compatible date string, like so:

$date = DateTime::createFromFormat('d/m/Y H:i:s', $yourDateString);
$dateToBeInserted = $date->format('Y-m-d H:i:s');
Sign up to request clarification or add additional context in comments.

Comments

2

Write a function to convert date,

function sqldate($date)
{
   $sql_date = date('Y-m-d H:i:s',strtotime($date));
   return $sql_date;
}

And your query look like,

$query = "INSERT INTO tableName (dateColumn) VALUES('".sqldate($date)."') ";

3 Comments

strtotime() will treat xx/yy/zz as a US format date(mm/dd/yy) rather than as UK format (dd/mm/yy)... you'll need to replace / with - for a UK date to be recognised correctly (dd-mm-yy)
for some reason, if I echo the string Im getting:
@user2370078 Let me know what you are passing to the function?
0

You can convert it using STR_TO_DATE() along with your INSERT statement, eg.

INSERT INTO tableName (dateColumn)
VALUES(STR_TO_DATE('dd/MM/yy hh:mm:ss','%d/%m/%y %H:%i:%s'))

Comments

0

Try this:

$parsedDate = date('Y-m-d H:i:s', strtotime($yourDate));
// Insert $parsedDate into your table column Date

1 Comment

strtotime() will treat xx/yy/zz as a US format date(mm/dd/yy) rather than as UK format (dd/mm/yy)... you'll need to replace / with - for a UK date to be recognised correctly (dd-mm-yy)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.