How To Convert Java.Sql.Date To Java.Util.Date Inwards Coffee - Jdbc Example
You oft demand to convert java.sql.Date to java.util.Date piece interacting alongside databases from Java application. Since JDBC the Java API for database connectivity uses java.sql.Date to correspond too most of the coffee code accepts java.util.Date, y'all receive got no alternative but to convert SQL engagement to util engagement inwards Java. Though, at that spot is simply about cardinal departure betwixt them e.g. java.sql.Date solely contains engagement purpose e.g. day, month, too year, it doesn't incorporate whatever fourth dimension attributes, but java.util.Date contains both engagement too fourth dimension attributes e.g. hour, minutes, seconds too milliseconds. So, when y'all convert a java.sql.Date to java.util.Date, the resultant java.util.Date instance has the fourth dimension purpose equally null i.e 00:00:00 to reverberate midnight.
Btw, I am going to utilization the same play a joke on to convert an SQL engagement to util date, which nosotros receive got used inwards the first part to convert java.util.Date to java.sql.Date. The play a joke on involves getTime() method which returns the discover of milliseconds from Epoch time.
Since both java.util.Date too java.sql.Date tin last created past times passing long millisecond value, this method acts equally a couple betwixt 2 unlike course of pedagogy from java.sql bundle too java.util package. It's 1 of the must-know techniques for coffee programmers working inwards JDBC. As y'all tin utilization this to convert java.sql.Date to java.sql.Timestamp equally well, equally shown inwards the earlier article.
One of the of import affair to know most java.sql.Date is that it's a subclass of java.util.Date, don't believe me? You tin banking concern jibe the source code of java.sql.Date course of pedagogy past times yourself, y'all volition honour "public course of pedagogy Date extends java.util.Date".
This reminds me an former incident, I used to instruct Java long dorsum too I think when I was teaching most SQL engagement to Util engagement conversion, 1 of my educatee asked me, why do nosotros demand to convert java.sql.Date to java.util.Date if it's subclass, can't nosotros simply move past times it guide to a method expecting java.util.Date?
Good question? No, I similar this sort of enquiry too educatee because it shows they are non simply listening but likewise applying their mind, to last honest, it's real important. Every novel information should last validated against existing information nosotros know. This makes learning fast too improves reasoning skill.
The reply is no, y'all cannot move past times java.sql.Date to a method which is expecting java.util.Date. Even though Inheritance volition allow y'all to move past times because it's a subclass, it could intermission your code because java.sql.Date violates the Liskov Substitution principle. This regulation states that a subclass tin stand upwardly inwards house of the raise class, which java.sql.Date does non follow.
In companionship to confirm alongside the Definition of SQL DATE, the millisecond values wrapped past times a java.sql.Date instance is normalized past times setting the fourth dimension purpose e.g. hours, minutes, seconds, too milliseconds to null inwards the item fourth dimension zone alongside which the instance is associated. This agency all time-related method either throws java.lang.IllegalArgumetnException equally shown below:
If the method which is expecting a java.util.DaAte calling the getHours() method, thence it volition intermission when y'all move past times a java.sql.Date object. This is why it's of import for a course of pedagogy to obey Liskov exchange principle. See Core Java Volume 2 - Advanced Features past times Cay S. Horstmann to larn to a greater extent than most SQL engagement too fourth dimension classes.
This method supply today's engagement which y'all tin read using getDate() method of ResultSet. This gives y'all an instance of java.sql.Date. After that nosotros cal the getTime() method of java.sql.Date too move past times that long millisecond value to java.util.Date to create an instance of util date. Since SQL engagement doesn't receive got a fourth dimension purpose your tin run across the util engagement likewise has fourth dimension purpose equally zero.
You tin run across that fourth dimension purpose is ever null when y'all convert java.sql.Date to java.util.Date because SQL engagement doesn't receive got whatever fourth dimension chemical ingredient inwards it.
Here is a squeamish summary of SQL engagement too fourth dimension classes from JDBC API:
That's all most how to convert java.sql.Date to java.util.Date inwards Java. It's easy, y'all simply demand to think most getTime() method, which is a couple betwixt the 2 engagement classes from unlike API. You should likewise proceed inwards remove heed to utilization fully qualified get upwardly of Date classes e.g. java.sql.Date too java.util.Date instead of writing simply Date, equally it may create confusion to both compiler too boyfriend programmer. It's a best practise to utilization the fully qualified get upwardly to avoid ambiguity when nosotros receive got 2 classes alongside the same get upwardly used inwards the same class.
Other JDBC tutorials for Java Programmers
Further Learning
JSP, Servlets too JDBC for Beginners: Build a Database App
Complete JDBC Programming Part 1 too 2
Java Platform: Working alongside Databases Using JDBC
Btw, I am going to utilization the same play a joke on to convert an SQL engagement to util date, which nosotros receive got used inwards the first part to convert java.util.Date to java.sql.Date. The play a joke on involves getTime() method which returns the discover of milliseconds from Epoch time.
Since both java.util.Date too java.sql.Date tin last created past times passing long millisecond value, this method acts equally a couple betwixt 2 unlike course of pedagogy from java.sql bundle too java.util package. It's 1 of the must-know techniques for coffee programmers working inwards JDBC. As y'all tin utilization this to convert java.sql.Date to java.sql.Timestamp equally well, equally shown inwards the earlier article.
One of the of import affair to know most java.sql.Date is that it's a subclass of java.util.Date, don't believe me? You tin banking concern jibe the source code of java.sql.Date course of pedagogy past times yourself, y'all volition honour "public course of pedagogy Date extends java.util.Date".
This reminds me an former incident, I used to instruct Java long dorsum too I think when I was teaching most SQL engagement to Util engagement conversion, 1 of my educatee asked me, why do nosotros demand to convert java.sql.Date to java.util.Date if it's subclass, can't nosotros simply move past times it guide to a method expecting java.util.Date?
Good question? No, I similar this sort of enquiry too educatee because it shows they are non simply listening but likewise applying their mind, to last honest, it's real important. Every novel information should last validated against existing information nosotros know. This makes learning fast too improves reasoning skill.
The reply is no, y'all cannot move past times java.sql.Date to a method which is expecting java.util.Date. Even though Inheritance volition allow y'all to move past times because it's a subclass, it could intermission your code because java.sql.Date violates the Liskov Substitution principle. This regulation states that a subclass tin stand upwardly inwards house of the raise class, which java.sql.Date does non follow.
In companionship to confirm alongside the Definition of SQL DATE, the millisecond values wrapped past times a java.sql.Date instance is normalized past times setting the fourth dimension purpose e.g. hours, minutes, seconds, too milliseconds to null inwards the item fourth dimension zone alongside which the instance is associated. This agency all time-related method either throws java.lang.IllegalArgumetnException equally shown below:
public int getHours() { throw new java.lang.IllegalArgumentException(); }
If the method which is expecting a java.util.DaAte calling the getHours() method, thence it volition intermission when y'all move past times a java.sql.Date object. This is why it's of import for a course of pedagogy to obey Liskov exchange principle. See Core Java Volume 2 - Advanced Features past times Cay S. Horstmann to larn to a greater extent than most SQL engagement too fourth dimension classes.
java.sql.Date to java.util.Date Conversion - Example
Now, let's run across our sample Java programme to convert a java.sql.Date to java.util.Date inwards JDBC code. In this program, nosotros are connecting to Microsoft SQL Server too thence telephone band the Microsoft SQL Server's GETDATE() method using a PreparedStatement.This method supply today's engagement which y'all tin read using getDate() method of ResultSet. This gives y'all an instance of java.sql.Date. After that nosotros cal the getTime() method of java.sql.Date too move past times that long millisecond value to java.util.Date to create an instance of util date. Since SQL engagement doesn't receive got a fourth dimension purpose your tin run across the util engagement likewise has fourth dimension purpose equally zero.
import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; /* * Java Program to convert java.sql.Date to java.util.Date * inwards JDBC. */ public class SQLToUtilDate{ public static void main(String[] args) { java.sql.Date sqlDate = readDateFromDatabase(); java.util.Date utilDate = new java.util.Date(sqlDate.getTime()); System.out.println("sql engagement from database: " + sqlDate); System.out.println("util engagement inwards Java: " + utilDate); } public static java.sql.Date readDateFromDatabase() { Connection con = null; java.sql.Date dateFromDatabse = 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, "root", "root"); PreparedStatement ps = con.prepareStatement("select GETDATE()"); ResultSet rs = ps.executeQuery(); rs.next(); // motion the cursor to origin column dateFromDatabse = rs.getDate(1); } catch (Exception e) { e.printStackTrace(); } return dateFromDatabse; } } Output 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 sql engagement from database: 2016-06-17 utl engagement in Java: Friday Jun 17 00:00:00 PDT 2016
You tin run across that fourth dimension purpose is ever null when y'all convert java.sql.Date to java.util.Date because SQL engagement doesn't receive got whatever fourth dimension chemical ingredient inwards it.
Here is a squeamish summary of SQL engagement too fourth dimension classes from JDBC API:
That's all most how to convert java.sql.Date to java.util.Date inwards Java. It's easy, y'all simply demand to think most getTime() method, which is a couple betwixt the 2 engagement classes from unlike API. You should likewise proceed inwards remove heed to utilization fully qualified get upwardly of Date classes e.g. java.sql.Date too java.util.Date instead of writing simply Date, equally it may create confusion to both compiler too boyfriend programmer. It's a best practise to utilization the fully qualified get upwardly to avoid ambiguity when nosotros receive got 2 classes alongside the same get upwardly used inwards the same class.
Other JDBC tutorials for Java Programmers
- Top 10 JDBC Best Practices Every Programmer Should Follow (list)
- How to convert java.util.Date to java.sql.Date inwards JDBC? (example)
- Top 10 JDBC Interview Questions for Programmers (list)
- 6 tips to amend surgery Java Database layer? (tips)
- How to utilization DAO (Data Access Object) pattern pattern inwards Java? (answer)
- How to connect MySQL database from Java? (guide)
Further Learning
JSP, Servlets too JDBC for Beginners: Build a Database App
Complete JDBC Programming Part 1 too 2
Java Platform: Working alongside Databases Using JDBC
0 Response to "How To Convert Java.Sql.Date To Java.Util.Date Inwards Coffee - Jdbc Example"
Post a Comment