I have a MySQL database
, with a column that is date type DATETIME
.
I am getting a string value for a date / time from an external application. That string value looks like this:
'5/15/2012 8:06:26 AM'
MySQL throws an error on the INSERT: "Error. Incorrect datetime value"
. My workaround was to change the column type to VARCHAR
, which works, but I really need the data as a proper Date & Time for future use.
I researched accepted formatting for MySQL DATETIME
values, and found that MySQL
wants the DATETIME
format as 'YYYY-MM-DD HH:MM:SS'
.
I can't change the external application to reformat the date / time string in a format, so my only chance is to deal with it.
What I need to do, I think, is parse the existing string, using MySQL syntax
, inside of my INSERT
statement, but I'm not sure how to do that. I have some idea that I need to use a SELECT
clause, perhaps STR_TO_DATE
, somehow in combination with my INSERT statement.
Here is my current INSERT statement. I removed the other fields that are not causing a problem, just to make the example clean.
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES ('5/15/2012 8:06:26')
STR_TO_DATE() : This function in MySQL helps to convert string values to date or time or DateTime values. The function will return zero (0000-00-00) if an empty string is passed as an argument.
MySQL STR_TO_DATE() Function The STR_TO_DATE() function returns a date based on a string and a format.
In Oracle, TO_DATE function converts a string value to DATE data type value using the specified format. In MySQL, you can use STR_TO_DATE function. Note that the TO_DATE and STR_TO_DATE format strings are different.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES (STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With