• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java date to MySQL date conversion

 
Sangeetha Rao
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Sangeetha Rao
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
dhaval thakor
Ranch Hand
Posts: 53
Eclipse IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your post is saved my couple hours..

Thank you very much.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic