Difference between java.sql.Time, java.sql.Timestamp and java.sql.Date is most common JDBC question appearing on many core Java interviews. As JDBC provides three classes java.sql.Date, java.sql.Time and java.sql.Timestamp to represent date and time and you already have java.util.Date which can represent both date and time, this question poses lot of confusion among Java programmer and that’s why this is one of those tricky Java questions which is tough to answer. It becomes really tough if differences between them is not understood correctly. We have already seen some frequently asked or common JDBC questions like why JDBC has java.sql.Date despite java.util.Date and Why use PreparedStatement in Java in our last tutorials and we will see difference between java.sql.Date, java.sql.Time and java.sql.Timestamp in this article. By the way apart from these JDBC interview questions, if you are looking to get most from JDBC you can also see 4 JDBC performance tips and 10 JDBC best practices to follow. Those article not only help you to understand and use JDBC better but also help on interviews. Let’s come back to difference sql time, timestamp and sql date.
Difference between java.sql.Time, java.sql.Timestamp and java.sql.Date:
JDBC in Java has three date/time types corresponding to DATE, TIME and TIMESTAMP type of ANSI SQL. These types are used to convert SQL types into Java types.
1) First difference on java.sql.Time vs java.sql.Timestamp vs java.sql.Date is about information they represent :
JDBC TIME or java.sql.Time represent only time information e.g. hours, minutes and seconds without any date information.
JDBC DATE or java.sql.Date represent only date information e.g. year, month and day without any time information.
JDBC TIMESTAMP or java.sql.Timestamp represent both date and time information including nanosecond details.
2) java.sql.Time and java.sql.Timestamp extends java.util.Date class but java.sql.Date is independent.
3) Time information from java.sql.Date and Date information from java.sql.Time is normalized and may set to zero in order to confirm ANSI SQL DATE and TIME types.
So difference between Time, Timestamp and Date of SQL package is clear in terms of what they represent. On contrary java.util.Date also represent Date and time information but without nanosecond details and that's why many people prefer to store date as long value (millisecond passed from epoch January 1, 1970 00:00:00.000 GMT). If you compare to java.sql.Timestamp with equals() method it will return false as value of nanosecond is unknown.
That's all on difference between java.sql.Date, java.sql.Time and java.sql.Timestamp. All differences lies on what exactly the represent. This kinds of questions are worth looking before going to any JDBC interview as time and date are integral part of any JDBC interview.
Other JDBC and SQL articles from Javarevisited Blog