Many java developers may have this question ‘java.util.Date is there to represent date, why again java.sql.Date class is given by Java?’ in mind. In this post, I am going to address this question.
Note: java.sql.Date is a sub class of java.util.Date.
Before answering this question, let’s try to understand how sql handle the date and time.
SQL support following data types for storing a date or a date/time value.
Data Type | Format |
DATE | YYYY-MM-DD |
DATETIME | YYYY-MM-DD HH:MI:SS |
TIMESTAMP | YYYY-MM-DD HH:MI:SS |
YEAR | YYYY or YY |
As you see, DATE type, it stores only year, month and day. It do not store the time (like hour, minute, second). But in case of ‘java.util.Date’, it stores the time also. To address this issue, java.sql.Date come into picture. It maintains the semantics with respect to DATE type of SQL.
Let’s see it with an example.
Application.java
package com.sample.app;
public class Application {
public static void main(String args[]) {
java.util.Date today = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(today.getTime());
java.util.Date utilDate = new java.util.Date(today.getTime());
System.out.println("Sql Date : " + sqlDate);
System.out.println("Util Date : " + utilDate);
}
}
Output
Sql Date : 2018-09-16
Util Date : Sun Sep 16 10:40:07 IST 2018
Note: java.sql.Date is a sub class of java.util.Date.
Below table summarizes the SQL date related types and corresponding mapping classes provided by java.
SQL Type | Java Class |
DATE | java.sql.Date |
TIME | java.sql.Time |
TIMESTAMP | java.sql.Timestamp |
You may like
Interview Questions
Programming Questions
Miscellaneous
Different ways to dynamically load a class
Class.forName vs ClassLoader.loadClass
How the jdbc driver is loaded?
Can I overload main method of a class?
Can I throw an exception from static block?
Does yield method releases the lock?
Can I call a run method of thread class directly?
This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here