How to convert Timestamp to Date inwards Java -JDBC Example Tutorial

In the final article, I lead keep shown yous how to convert Date to Timestamp inwards Java together with today we'll larn nearly converting timestamp value from database to Date inwards Java. As yous remember, the JDBC API uses dissever Date, Time together with Timestamp degree to confirm DATE, TIME together with DATETIME information type from the database, but most of the Java object oriented code is written inwards java.util.Date. This agency yous remove to know how to convert the timestamp to appointment together with vice-versa. You tin practise yesteryear using the getTime() method, which furnish the reveal of millisecond from Epoch value. This tin endure used to practise both Timestamp together with java.util.Date, hence it acts as a span betwixt Date degree from java.util bundle together with Date, Time together with Timestamp degree from the java.sql package. Like Date, Timestamp every bit good contains both appointment together with fourth dimension value, then yous won't come across empty or null fourth dimension nosotros saw previously piece converting SQL Date to java.util.Date.

As I lead keep said before, fifty-fifty though classes from java.sql bundle extends java.util.Date, including Timestamp they cannot endure used inwards house of java.util.Date. Some of yous may inquire why? Since Timestamp has both appointment together with fourth dimension value, it should endure able to acts every bit Date, nosotros sympathize nearly java.sql.Date non having fourth dimension element but amongst Timestamp nosotros lead keep both.

Well, that's ane time again a really proficient reasoning together with directs your hear to notice the missing role of why yous cannot usage Timestamp inwards house of date fifty-fifty if it has both appointment together with fourth dimension part. The respond lies inwards the Java documentation itself. The Timestamp degree is a composite of java.util.Date together with an additional nanoseconds values, required to concord the SQL TIMESTAMP fractional seconds value. If yous facial expression at the implementation of Timestamp class, yous volition notice that alone 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 element of a appointment is unknown. As a result, the Timestamp.equals(Object) method is not symmetric amongst honour to the java.util.Date.equals(Object) method, hence it every bit good violates the contract of equals method. Also, the hashCode method uses the underlying java.util.Date implementation together with thus does non include nanos inwards its computation.

Btw, If yous desire to refresh your concepts of equals together with hashcode, I advise yous reading Effective Java, where Joshua Bloch has discussed it inwards bang-up detail.

So fifty-fifty though, methods similar getHours(), getMinutes(), getSeconds() doesn't throw IllegalArgumentException, because of these differences, yous nonetheless should non usage a Timestamp value inwards house of java.util.Date. The inheritance human relationship betwixt Timestamp together with java.util.Date actually denotes implementation inheritance, together with non type inheritance.




Java Program to convert Timestamp to Date amongst example

Now, let's come across our sample Java plan to convert a Timestamp value to Date inwards Java. In this example, our Java plan connects to the Microsoft SQL server together with telephone telephone the CURRENT_TIMESTAMP method using PreparedStatment object. This method returns the electrical current database organisation timestamp every bit a DATETIME value withtout the database fourth dimension zone offsert. This value is derived from the operating sytsem of the reckoner on which the instance of SQL Server is running (see SQL fundamentals).

When nosotros read this value inwards Java using ResultSet, nosotros usage the getTimestamp() method together with exceed it the column index. If yous remember, columns inwards JDBC API starts amongst 1 instead of zero, nosotros exceed 1. We every bit good remove to telephone telephone the next() method of ResultSet to motion the cursor to the outset element, otherwise yous won't the right value. Once yous got the java.sql.Timestamp value, but telephone telephone the getTime() together with practise a java.util.Date instnace using that. Now, yous lead keep successfully converted a java.sql.Timestamp value to java.util.Date value.

how to convert Date to Timestamp inwards Java How to convert Timestamp to Date inwards Java -JDBC Example Tutorial



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 outset 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 current 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 twosome of of import things to larn inwards this program, first, I lead keep non called the Class.forName() method to explicitly charge the JDBC driver because from Java 1.6 onward, it tin endure automatically loaded yesteryear JVM. The 2nd of import matter is the usage of setting the logger for DriverManager, which volition impress of import details e.g. which JDBC driver it is loading together with which host together with port it is connecting to database.

The code to convert Timestamp into a java.util.Date is within main() method, yous tin come across it's quite simple, but lead keep the long millisecond value yesteryear calling getTime() on Timestamp together with exceed it to Date constructor, that's it, yous are done.

You tin farther read Core Java, Volume II--Advanced Features yesteryear Cay S. Horstmann to larn to a greater extent than nearly JDBC driver together with other JDBC concepts, ane of the most useful books to larn Java concepts.




Important points

- Timestamp degree has both appointment together with fourth dimension value every bit Date but cannot endure used inwards house of java.util.Date becaues of additional nanosecond value it supports.

- The Timestamp.equals(Object) method volition furnish false if yous compare Timestamp amongst Date, this is ane of the reasons you cannot usage Timestamp inwards house of Date inwards Java.

- The Timestamp degree has "s" instead of "S" which yous powerfulness facial expression given most of the Java classes are written using Camel case. Another ane is Hashtable amongst "t" intead of "T"

- Columns are started amongst index 1 instead of null hence getTimestamp(1) is used. This is non but related to Timestamp but related to ResultSet inwards JDBC together with yous must yell upwards this to avoid java.sql.SQLException: invalid column index, which oftentimes comes when a programmer tries to access the outset column amongst index zero, which is invalid.

- Don't forget to telephone telephone ResultSet.next() method earlier calling get() fifty-fifty if it contains but ane row. It is required to motion the cursor to outset element. It's a tricky concept to master copy but if yous don't know the right way to banking concern gibe if ResultSet is empty or not, yous volition combat to write robust JDBC code inwards future.


That's all nearly how to convert a Timestamp to Date inwards Java. As a programmer working amongst Java, JDBC together with database yous must know these details nearly Timestamp together with Date class, its imperative to write right JDBC code. Unfortunately, Java could lead keep done ameliorate chore yesteryear standaring things, every bit it's a drawback of an API, if programmer needs to yell upwards then many special cases.

Subscribe to receive free email updates:

0 Response to "How to convert Timestamp to Date inwards Java -JDBC Example Tutorial"

Posting Komentar