2

I have a field in MySQL created_on with datatype DATETIME. For that field, I have to insert the current date and time. I have taken java.util.Date object.

Date dateobj = new Date()
String query = "insert into users(created_on) values(?)";
ps = con.prepareStatement(query);
ps.setDate(1, new java.sql.Date(dateobj.getTime()));
insert_flag=ps.executeUpdate();

The query is executing fine but it is inserting only current date with 00:00:00. I want current date and time (example: 2015-10-28 03:23:50)

1 Answer 1

1

To insert a date and a time, you need to use setTimestamp instead of setDate and the datatype of your database column must be DATETIME (or TIMESTAMP).

Quoting setDate Javadoc:

The driver converts this to an SQL DATE value when it sends it to the database.

and quoting MySQL documentation:

The DATE type is used for values with a date part but no time part.

Working code:

ps.setTimestamp(1, new java.sql.Timestamp(new Date().getTime()));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.