The difference between java.util.Date and java. SQL.Date

  • 2020-04-01 03:58:50
  • OfStack

I used a date type in my database. When programming in Java, I import java.util.* and java. SQL.*, and I find that the Date type is directly declared

The Date dt.

An error is reported. I looked it up and found java.util.date and java.sql.Date.


java.util.Date udt;

java.sql.Date sdt;

Then I looked up the difference and usage between java.util.Date and java. SQL. Later I also used String to java.sql.date, which can also be found on the Internet, and I briefly introduced one of my favorite methods.

First of all, prepare a SimpleDateFormat object, use a SimpleDateFormat classes need to import the Java. Text. SimpleDateFormat

SimpleDateFormat df = new SimpleDateFormat(" yyyy-mm-dd "); // yyyy-mm-dd is the date format we want to convert to, and the converted string should be written in this format

Then, prepare a java.util.date object and a string to be converted


String str = " 2011-06-30 " ;//This cannot be written as 2011/06/30 or anything else, it will report an error, only the target date format yyyy-mm-dd
java.util.Date udt = null;

STR is then converted to java.util.date with df and assigned to udt


udt = df.parse(str);

Then we get the java.sql.date we need from udt


java.sql.Date sdt = new java.sql.Date(udt.getTime());

To sum up, we first use SimpleDateFormat to format the string to be converted to Date into java.util.Date type, and then from the Java. Util. Date object to get 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;
} 

The above is all the content of this article, I hope you can enjoy it.


Related articles: