The date type is used in my database. Java programming when the import of java.util.* and java.sql.*, found that the direct declaration of the date type
Date DT;
will be an error, check to find that there are java.util.Date and java.sql.Date, when defining the date type to use the full name, is like this:
Java.util.Date UDT;
Java.sql.Date SDT;
Then I check java.util.Date and java.sql.Date the difference and usage, this aspect of online information is very full, I will not repeat, the general difference is java.util.Date support date and time, and java.sql.Date only support the date. I also used the string to turn java.sql.Date, this can be found on the Internet, I briefly introduce a method I prefer.
First, prepare a SimpleDateFormat object and use the SimpleDateFormat class to import Java.text.SimpleDateFormat
SimpleDateFormat df = new SimpleDateFormat ("Yyyy-mm-dd"),//YYYY-MM-DD is the date format we want to convert, and the string to be converted in a moment should be written in this format as well.
Then, prepare a Java.util.Date object and the string to be converted
String str = "2011-06-30";//This can not be written in 2011/06/30 or other appearance, will be error, can only be yyyy-mm-dd by the target date format
Java.util.Date UDT = null;
The STR is then converted to java.util.Date with DF and assigned to the UDT
UDT = Df.parse (str);
And then get the java.sql.Date we need from the UDT.
Java.sql.Date SDT = new Java.sql.Date (Udt.gettime ());
To summarize is to use SimpleDateFormat to convert the string to be converted to a date into a java.util.Date type, and then from the resulting Java.util.Date object to get the Java.sql.Date object, we can write it as a function, the code is as follows:
Public java.sql.Date stringtosqldate (String str) {
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd");
Java.util.Date Udt=null;
try{
UDT = Sdf.parse (str);
}catch (Exceprion e) {
E.printstacktrace ();
}
Java.sql.Date SDT = new Java.sql.Date (Udt.gettime ());
return SDT;
}
Java.util.Date and Java.sql.Date