wood burning stoves 2.0*
The moose likes JDBC and the fly likes a bit comfused about java.util.Date and java.sql.Date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "a bit comfused about java.util.Date and java.sql.Date" Watch "a bit comfused about java.util.Date and java.sql.Date" New topic

a bit comfused about java.util.Date and java.sql.Date

David Nelson

Joined: Nov 13, 2003
Posts: 22
I defined my registerDate field as a Date type, more specific, a java.util.Date, when i retrive data from database, it is fine:


but when i want to save it back to database:
ps.setDate(7,user.getRegisterDate()); cannot compile it because it is not expected Date type, why is there no problem with the first statement. for the second statement, may i just simply cast its type? just like:

Santosh Maskar
Ranch Hand

Joined: Jul 02, 2003
Posts: 226
See the Dcoumetation for the util.data and Sql.data what it retruns
Sonny Gill
Ranch Hand

Joined: Feb 02, 2002
Posts: 1211


java.util.Date is like a timestamp, it stores date information as well as time information, whereas java.sql.Date is supposed to store only Date information, time information should have been set to 0 or whatever the equivalent of 0 should be. There is more information on that in the API docs.

Also, java.sql.Date is a subclass of java.util.Date, so any method that accepts java.util.Date will also accept a java.sql.Date, but a method defined with format parameter type java.sql.Date will not accept an argument of type java.util.Date.

You cannot cast it, unless the value was initially created as java.sql.Date, and then upcast to java.util.Date. Try something like

In this thread Peter van der Linden made some interesting observations about using java dates.


The future is here. It's just not evenly distributed yet. - William Gibson
Consultant @ Xebia. Sonny Gill Tweets
Prateek Kumar Singh

Joined: Jan 21, 2011
Posts: 29

Hi ,

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

change your date format and enjoy.

Prateek Singh
subject: a bit comfused about java.util.Date and java.sql.Date
Similar Threads
how to enter date object in ms access database
convert a String into Date with SimpleDateFormat
java.util.Date to java.sql.Date
Formatting Date Object
inserting date into ms access