1. SQL Time type go util time type
Principle: Java.sql.Date, Java.sql.Time, java.sql.Timestamp three classes are java.util.Date subclasses, so according to the design principle of polymorphism, the parent class refers to the sub-class object, can be directly converted.
That
Java.util.Date udate = new Java.sql.Date (0);
Or: java.util.Date udate = new Java.sql.Time (0);
Or: java.util.Date udate = new Java.sql.Timestamp (0);
Using the generic design Toutil () method:
Public Static extends java.util.date> java.util.Date toutil (T t) { = t; return date; }
2. Util time Type turn SQLL time type
Principle: The Java.util.Date class of the GetTime () method can easily get the current time of milliseconds, this long type of data is very important, is to instantiate three SQL time type constructor necessary parameters.
That
Long millionseconds = Java.util.Date.getTime ();
Java.sql.Date sdate = new Java.sql.Date (millionseconds);
Or: Java.sql.Time stime = new Java.sql.Time (millionseconds);
Or: Java.sql.Timestamp Stimestamp = new Java.sql.Timestamp (millionseconds);
Using the generic design Tosql () method:
First design an enumeration class type:
enum Type { DATE, time, TIMESTAMP }
It specifies the type of SQL time to get from the Tosql () method: the date corresponds to the java.sql.date,time corresponding to the java.sql.time,timestamp corresponding to the Java.sql.Timestamp.
Public Static<textendsJava.util.date>T Tosql (java.util.Date utildate, type type) {T T=NULL; LongMillionseconds =Utildate.gettime (); Switch(type) { CaseDate:t= (T)Newjava.sql.Date (millionseconds); Break; CaseTime:t= (T)NewJava.sql.Time (millionseconds); Break; CaseTimestamp:t= (T)NewJava.sql.Timestamp (millionseconds); Break; default: Break; } returnT; }
Java in the design of the date class first design the date in Util, with the emergence of large databases, the original date type can not meet the time type saved in the database, this is derived from the various time classes in SQL, the support of MySQL database makes java.sql.Date, Java.sql.Time and Java.sql.Timestamp were born. Oh, this is just my personal understanding.
Java.util.Date and Java.sql.Date, Java.sql.Time, Java.sql.Timestamp interchange