Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
David Nelson
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I defined my registerDate field as a Date type, more specific, a java.util.Date, when i retrive data from database, it is fine:

user.setregisterDate(rs.getDate("registerDate"));

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:
ps.setDate(7,(java.sql.Date)user.getRegisterDate());

Cheers.
 
Santosh Maskar
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See the Dcoumetation for the util.data and Sql.data what it retruns
 
Sonny Gill
Ranch Hand
Posts: 1211
IntelliJ IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David,

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.

cheers.
 
Prateek Kumar Singh
Ranch Hand
Posts: 30
Eclipse IDE Hibernate Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

cheers,
Prateek Singh
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic