In the final article, I receive got shown you lot
how to convert Date to Timestamp inwards Java as well as today we'll acquire nigh converting timestamp value from database to Date inwards Java. As you lot remember, the JDBC API uses split
Date,
Time as well as
Timestamp shape to confirm DATE, TIME as well as DATETIME information type from the database, but most of the Java object oriented code is written inwards
java.util.Date. This agency you lot demand to know how to convert the timestamp to appointment as well as vice-versa. You tin sack exercise past times using the
getTime() method, which furnish the publish of millisecond from Epoch value. This tin sack last used to exercise both
Timestamp as well as
java.util.Date, hence it acts as a span betwixt Date shape from
java.util parcel as well as Date, Time as well as Timestamp shape from the
java.sql package. Like Date,
Timestamp besides contains both appointment as well as fourth dimension value, then you lot won't come across empty or null fourth dimension nosotros saw previously piece converting SQL Date to java.util.Date.
As I receive got said before, fifty-fifty though classes from java.sql parcel extends java.util.Date, including Timestamp they cannot last used inwards house of
java.util.Date. Some of you lot may enquire why? Since Timestamp has both appointment as well as fourth dimension value, it should last able to acts every bit Date, nosotros empathise nigh
java.sql.Date non having fourth dimension gene but amongst Timestamp nosotros receive got both.
Well, that's in 1 lawsuit to a greater extent than a really expert reasoning as well as directs your heed to detect the missing business office of
why you lot cannot role Timestamp inwards house of date fifty-fifty if it has both appointment as well as fourth dimension part. The response lies inwards the Java documentation itself. The Timestamp shape is a composite of
java.util.Date as well as an additional nanoseconds values, required to check the SQL TIMESTAMP fractional seconds value. If you lot aspect at the implementation of Timestamp class, you lot volition detect that exclusively integral seconds are stored inwards the
java.util.Date component. The fractional seconds - the nanos - are separate.
The
Timestamp.equals(Object) method never returns truthful when passed an object that isn't an instance of
java.sql.Timestamp e.g.
Timestamp.equals(date) volition furnish
false fifty-fifty if they comprise same value because the nanos gene of a appointment is unknown. As a result, the
Timestamp.equals(Object) method is
not symmetric amongst abide by to the
java.util.Date.equals(Object) method, hence it besides violates the
contract of equals method. Also, the hashCode method uses the underlying
java.util.Date implementation as well as thence does non include nanos inwards its computation.
Btw, If you lot desire to refresh your concepts of equals as well as hashcode, I advise you lot reading
Effective Java, where Joshua Bloch has discussed it inwards slap-up detail.
So fifty-fifty though, methods similar
getHours(),
getMinutes(),
getSeconds() doesn't throw
IllegalArgumentException, because of these differences, you lot withal should non role a Timestamp value inwards house of java.util.Date. The inheritance human relationship betwixt Timestamp as well as java.util.Date actually denotes implementation inheritance, as well as non type inheritance.
Java Program to convert Timestamp to Date amongst example
Now, let's come across our sample Java programme to
convert a Timestamp value to Date inwards Java. In this example, our Java programme connects to the Microsoft SQL server as well as telephone phone the
CURRENT_TIMESTAMP method using
PreparedStatment object. This method returns the electrical flow database organization timestamp every bit a
DATETIME value withtout the database fourth dimension zone offsert. This value is derived from the operating sytsem of the figurer on which the instance of SQL Server is running (see SQL fundamentals).
When nosotros read this value inwards Java using ResultSet, nosotros role the
getTimestamp() method as well as transcend it the column index. If you lot remember, columns inwards
JDBC API starts amongst 1 instead of zero, nosotros transcend 1. We besides demand to telephone phone the
next() method of
ResultSet to motion the cursor to the start element, otherwise you lot won't the right value. Once you lot got the
java.sql.Timestamp value, merely telephone phone the
getTime() as well as exercise a
java.util.Date instnace using that. Now, you lot receive got successfully converted a
java.sql.Timestamp value to
java.util.Date value.
Program to convert Timestamp to Date inwards Java import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.Date; /* * Java Program to convert Timestamp to Date inwards JDBC. */ public class Pattern { public static void main(String[] args) { Timestamp timestamp = timeStampFromDatabase(); Date appointment = new java.util.Date(timestamp.getTime()); System.out.println("current timestamp from database: " + timestamp); System.out.println("converted appointment inwards Java: " + date); } public static Timestamp timeStampFromDatabase() { Connection con = null; Timestamp currentTimeStamp = null; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String url = "jdbc:sqlserver://localhost:42588;"; DriverManager.setLogWriter(new PrintWriter(System.out, true)); con = DriverManager.getConnection(url, "sa", "root"); PreparedStatement ps = con.prepareStatement("select CURRENT_TIMESTAMP"); ResultSet rs = ps.executeQuery(); rs.next(); // motion the cursor to start column currentTimeStamp = rs.getTimestamp(1); } catch (Exception e) { e.printStackTrace(); } return currentTimeStamp; } } Output DriverManager.getConnection("jdbc:sqlserver://localhost:42588;") trying sun.jdbc.odbc.JdbcOdbcDriver *Driver.connect (jdbc:sqlserver://localhost:42588;) trying com.microsoft.sqlserver.jdbc.SQLServerDriver getConnection returning com.microsoft.sqlserver.jdbc.SQLServerDriver electrical flow timestamp from database: 2016-06-17 13:13:56.61 converted appointment in Java: Friday Jun 17 13:13:56 PST 2016 Influenza A virus subtype H5N1 span of of import things to acquire inwards this program, first, I receive got non called the
Class.forName() method to explicitly charge the
JDBC driver because from Java 1.6 onward, it tin sack last automatically loaded past times JVM. The minute of import affair is the role of setting the logger for
DriverManager, which volition impress of import details e.g. which JDBC driver it is loading as well as which host as well as port it is connecting to database.
The code to convert Timestamp into a
java.util.Date is within
main() method, you lot tin sack come across it's quite simple, merely receive got the long millisecond value past times calling
getTime() on Timestamp as well as transcend it to Date constructor, that's it, you lot are done.
You tin sack farther read
Core Java, Volume II--Advanced Features past times Cay S. Horstmann to acquire to a greater extent than nigh JDBC driver as well as other JDBC concepts, 1 of the most useful books to acquire Java concepts.
Important points
- Timestamp shape has both appointment as well as fourth dimension value every bit Date but cannot last used inwards house of java.util.Date becaues of additional nanosecond value it supports.
- The
Timestamp.equals(Object) method volition furnish
false if you lot compare Timestamp amongst Date, this is 1 of the reasons
you cannot role Timestamp inwards house of Date inwards Java.
- The Timestamp shape has
"s" instead of
"S" which you lot powerfulness aspect given most of the Java classes are written using Camel case. Another 1 is
Hashtable amongst
"t" intead of
"T" - Columns are started amongst index 1 instead of null hence
getTimestamp(1) is used. This is non merely related to Timestamp but related to ResultSet inwards JDBC as well as you lot must retrieve this to avoid
java.sql.SQLException: invalid column index, which oftentimes comes when a programmer tries to access the start column amongst index zero, which is invalid.
- Don't forget to telephone phone
ResultSet.next() method earlier calling
get() fifty-fifty if it contains merely 1 row. It is required to motion the cursor to start element. It's a tricky concept to master copy but if you lot don't know the
right way to cheque if ResultSet is empty or not, you lot volition grapple to write robust JDBC code inwards future.
That's all nigh
how to convert a Timestamp to Date inwards Java. As a programmer working amongst Java, JDBC as well as database you lot must know these details nigh Timestamp as well as Date class, its imperative to write right JDBC code. Unfortunately, Java could receive got done ameliorate undertaking past times standaring things, every bit it's a drawback of an API, if programmer needs to retrieve then many special cases.
Further Learning Complete Java Masterclass Java Fundamentals: The Java Language Java In-Depth: Become a Complete Java Engineer!