I want to insert the current date and time into a columns defined as datetime type.
I typed the following code:
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
PrepStmt.setDate(1, sqlDate);
When I check the database, I find that the date inserted correctly, but the time is: 00:00:00. What is the fix ?
In order to get "the current date" (as in today's date), you can use LocalDate. now() and pass that into the java. sql. Date method valueOf(LocalDate) .
INSERT INTO yourTableName(yourDateColumnName) VALUES(NOW()); If your column has datatype date then NOW() function inserts only current date, not time and MySQL will give a warning. To remove the warning, you can use CURDATE().
To insert only date value, use curdate() in MySQL. With that, if you want to get the entire datetime, then you can use now() method. Insert both date and time with the help of now().
Since you are using datetime
as your column type, you need to use java.sql.Timestamp
to store your date, and PrepareStatement.setTimestamp
to insert it.
Try using this: -
java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
PrepStmt.setTimestamp(1, date);
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