简体   繁体   English

如何在MySQL插入语句中正确使用str_to_date的多个实例?

[英]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. 我正在尝试将2个英国格式(dd / mm / yyyy)的日期插入MySQL US日期格式的MySQL数据库。

I am using str_to_date. 我正在使用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. 第一个str_to_date实例可以按预期工作,但是第二个实例始终插入与第一个str_to_date实例相同的日期,即使原始日期不同。

$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? 在MySQL插入语句中处理str_to_date的多个实例的正确方法是什么?

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()的格式字符串告诉MySQL第一个参数的日期值是哪种格式。这不是如何格式化进入mysql(例如目标)格式的值。 str_to_date's output is ALWAYS a native mysql date/time value, which is yyyy-mm-dd hh:mm:ss str_to_date的输出始终是本地mysql日期/时间值,即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. 因为您说的输入格式是monday/day ,但是提供了day/month值和NO time值,所以您得到的结果很奇怪。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM