aspose file tools*
The moose likes JDBC and the fly likes Java date to MySQL date conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Java date to MySQL date conversion" Watch "Java date to MySQL date conversion" New topic
Author

Java date to MySQL date conversion

Sangeetha Rao
Ranch Hand

Joined: Aug 01, 2005
Posts: 33
I want to insert the current date from my servlet into a column of type 'date' in a table in MySQL. How do I do that?

I tried this:

java.sql.Date sysdate = new java.sql.Date(
(new java.util.Date()).getTime());

and inserted 'sysdate', but the value of the column is '0000-00-00' after the insertion!
Prabhu Venkatachalam
Ranch Hand

Joined: Nov 16, 2005
Posts: 502

It is inserting default value. That is the reason its value inserted is '0000-00-00'.

I think you need to supply format of date you are passing to Database.


Have a look at this URL


Prabhu Venkatachalam<br />SCJP 1.4,SCWCD 1.4<br />prabhu.venkatachalam@gmail.com
Sangeetha Rao
Ranch Hand

Joined: Aug 01, 2005
Posts: 33
Thank you Prabhu,

The following code just solved the problem:

java.util.Date dt = new java.util.Date();

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String currentTime = sdf.format(dt);

This 'currentTime' was inserted into the column whose type was DateTime and it was successful.
Rahul Nair
Ranch Hand

Joined: Dec 01, 2007
Posts: 138
Hello Sangeetha,

Thank you very much. After a couple of hours my code for insertion datetime to database table is working fine.

I have searched many forums but i didn't get satisfactory solution but now according to your instruction changing prepStatement.setDate to prepStatement.setString is works fine.But i don't understand why i can't use prepStatement.setDate to store datetime to database ?


Thanks ones again ?
Great Work.

Thanks
Shilpa Tendulkar
Ranch Hand

Joined: Jul 29, 2001
Posts: 75
Hi,

If you are always inserting current date/time in the field, then I would suggest you to use timestamp as datatype for database field and set default to CURRENT_TIMSTAMP. This way you don't have to insert any date/time from java, MySQL will take care of inserting current date time.


SCJP5
dhaval thakor
Ranch Hand

Joined: Aug 27, 2012
Posts: 53

Your post is saved my couple hours..

Thank you very much.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Java date to MySQL date conversion