简体   繁体   English

如何使用java在mysql的datetime字段中插入当前日期

[英]how to insert current date in datetime field in mysql using java

I am working on date time using Java. 我正在使用Java处理日期时间。 I am trying to insert the current date in MySQL. 我正在尝试在MySQL中插入当前日期。 The data type for the table in database is datetime. 数据库中表的数据类型为datetime。 When I am trying to insert the data, an exception is thrown 当我尝试插入数据时,抛出异常

The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value. 从nvarchar数据类型到datetime数据类型的转换导致值超出范围。

I want to insert current date in in that field. 我想在该字段中插入当前日期。

It is recommended that you insert the current date using SQL rather than Java. 建议您使用SQL而不是Java插入当前日期。 To do so, use the MySQL CURDATE() function. 为此,请使用MySQL CURDATE()函数。 Your query will look like this: 您的查询将如下所示:

INSERT INTO orders (order_date, order_description)
     VALUES (CURDATE(), 'Jarlsberg Cheese');

Note that CURDATE() gives you the date only. 请注意,CURDATE()仅为您提供日期。 If you want the time you need to use NOW() , or CURTIME() : 如果需要时间,则需要使用NOW()CURTIME()

  • NOW() : Gives you the date and time, eg 2014-11-11 12:45:34. NOW() :给出日期和时间,例如2014-11-11 12:45:34。
  • CURDATE() : Gives you the date only, eg 2014-11-11. CURDATE() :仅提供日期,例如2014-11-11。
  • CURTIME() : Gives you the time only, eg 12:45:34. CURTIME() :仅给您时间,例如12:45:34。

You can use NOW() function of mysql. 您可以使用mysql的NOW()函数。 NOW() returns the current date and time. NOW()返回当前日期和时间。

Hope it will help you. 希望对您有帮助。 Happy coding. 快乐的编码。

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

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