Java. util. Date and Java. SQL. Date, java. SQL. Time, java. SQL. Timestamp interchange, java. SQL. timestamp
1. SQL time type to util time type
Principle: java. SQL. date, java. SQL. time, java. SQL. the three Timestamp classes are java. util. date subclass, so according to the design principle of polymorphism, the parent class reference points to the subclass object and can be directly converted.
That is:
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 );
Use the generic design toUtil () method:
public static <T extends java.util.Date> java.util.Date toUtil(T t){ java.util.Date date = t; return date; }
2. util time type to sqll time type
Principle: using java. util. the getTime () method of the Date class can easily obtain the number of milliseconds of the current time. This long type of data is crucial and is a necessary parameter for instantiating three SQL time constructors.
That is:
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 );
Use generic design toSql () method:
First, design an enumeration class Type:
enum Type { DATE, TIME, TIMESTAMP }
It specifies the SQL TIME type to be obtained from the toSql () method: DATE corresponds to java. SQL. Date, Time corresponds to java. SQL. TIME, TIMESTAMP corresponds to java. SQL. Timestamp.
public static <T extends java.util.Date> T toSql(java.util.Date utilDate, Type type) { T t = null; long millionSeconds = utilDate.getTime(); switch (type) { case DATE: t = (T) new java.sql.Date(millionSeconds); break; case TIME: t = (T) new java.sql.Time(millionSeconds); break; case TIMESTAMP: t = (T) new java.sql.Timestamp(millionSeconds); break; default: break; } return t; }
Java first designs the Date in util when designing the Date class. With the emergence of major databases, the original Date type cannot meet the time type stored in the database, in this way, various time classes in SQL are derived. The support for Mysql database makes java. SQL. date, java. SQL. time, java. SQL. timestamp came into being. This is just my personal understanding.
Why qldate is different from javautildate?
The upstairs is too complicated. It's easy to say!
Java. SQL. date type, output: year, month, day;
Java. util. date type, output: year, month, day, hour, minute, second;
Javasqltime javasqldate how to combine the two into a javautildate
Java. SQL. date only contains dates. Java. SQL. time only contains one time. Then you can use simpleDateFormat to parse the tostring according to the format parse.