简体   繁体   中英

How do you correctly use multiple instances of str_to_date with MySQL insert statement?

I am trying to insert 2 dates in UK format (dd/mm/yyyy) to a MySQL database in the MySQL US date format.

I am using str_to_date. The first instance of str_to_date works as expected, but the second instance always inserts the same date as the first instance of str_to_date, even though the original dates are different.

$date_1 = "10/01/2016";
$date_2 = "16/02/2016";

$sql = "INSERT INTO customers (date_1, date_2)
VALUES (STR_TO_DATE( '$date_1', '%m/%d/%Y %h:%i' ), STR_TO_DATE( '$date_2', '%m/%d/%Y %h:%i' ))";

What is the correct way of handling multiple instances of str_to_date in a MySQL insert statement?

Thank you

The format string of str_to_date() tells MySQL what format the first argument's date value is in. It's not how to format the value going in to mysql (eg the destination) format. str_to_date's output is ALWAYS a native mysql date/time value, which is yyyy-mm-dd hh:mm:ss

Since you're saying the input format is monday/day , but are providing day/month values and NO time values, you get wonky results.

Try

                         24/01/2016
STR_TO_DATE( '$date_1', '%d/%m/%Y' )

instead. Note the removal of the time format characters. Your input string has no time values at all.

mysql> select str_to_date('24/01/2016', '%m/%d/%Y %h:%i');
+---------------------------------------------+
| str_to_date('24/01/2016', '%m/%d/%Y %h:%i') |
+---------------------------------------------+
| NULL                                        |
+---------------------------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> select str_to_date('24/01/2016', '%d/%m/%Y');
+---------------------------------------+
| str_to_date('24/01/2016', '%d/%m/%Y') |
+---------------------------------------+
| 2016-01-24                            |
+---------------------------------------+
1 row in set (0.00 sec)

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