Thursday, December 12, 2019

How To Convert Java.Util.Date To Java.Sql.Date - Example

There are 2 appointment classes inwards Java, i inwards java.util package as well as other inwards the java.sql package. Though both are known every bit Date class, at that spot is some difference betwixt java.util.Date as well as java.sql.Date e.g. Former is used whenever a Date is required inwards Java application piece afterwards is used to read as well as shop DATE SQL type from the database. There is i to a greater extent than of import deviation is, java.util.Date stores both appointment as well as fourth dimension values, piece java.sql.date solely stores appointment information, without whatever fourth dimension part. As per Javadoc, java.sql.date is a sparse wrapper around a millisecond value that allows JDBC to position this every bit an SQL DATE value. To adjust amongst the Definition of SQL DATE, the millisecond values wrapped past times a java.sql.Date instance must last 'normalized' past times setting the hours, minutes, seconds, as well as milliseconds to zippo inwards the detail fourth dimension zone amongst which the instance is associated. See SQL appointment vs Util date for few to a greater extent than differences.

In this Java tutorial, nosotros volition larn how to convert a java.util.Date to java.sql.Date, every bit nosotros oftentimes require to create this when storing values into database. Since java.util.Date is measure agency to correspond appointment as well as fourth dimension inwards Java, I solely drib dead along java.sql.Date up-to JDBC or DAO Layer, past times the agency if you lot require appointment amongst time, as well as then usage SQL TIMESTAMP type instead of DATE.

It's likewise notable that java.sql.Date is subclass of java.util.Date, exactly it doesn't hateful you lot tin transcend around this inwards house of java.util.Date, because it violates Liskov Substitution principle.




All fourth dimension related methods of java.sql.Date throws IllegalArgumentException, every bit shown below


public int getHours() {     throw  java.lang.IllegalArgumentException(); }   public int getMinutes() {     throw new java.lang.IllegalArgumentException(); }   public int getSeconds() {     throw new java.lang.IllegalArgumentException(); }

It genuinely an interesting instance of Inheritance, where superclass is to a greater extent than powerful than subclass, as well as instead of extending functionalities of rear class, subclass is genuinely limiting characteristic past times non allowing fourth dimension fields. If you lot receive got a code, which accepts java.util.Date, compiler volition allow a java.sql.Date to last passed to that method, exactly every bit presently every bit you lot run the program, your code volition neglect amongst next mistake :

Exception inwards thread "main" java.lang.IllegalArgumentException     at java.sql.Date.getHours(Date.java:182)

That's why, brand certain non to permit java.sql.Date come upwardly exterior of Data Access layer. By the way, because both the flat has same cite Date, you lot tin non usage them together past times their uncomplicated name, you lot require to specify their fully character name, i.e. cite amongst package, every bit shown inwards below example. If nosotros import java.util.Date as well as then compiler volition process whatever Date every bit util appointment as well as non java.sql.Date.


Java Program to convert java.util.Date to java.sql.Date

Here is our sample programme for converting a util appointment to sql date. Since both Date classes are based upon long fourth dimension interval, you lot tin easily convert them past times passing value of getTime(), which correspond milliseconds passed from 1st Jan 1970, likewise known every bit EPOCH. Since java.sql.Date solely contains appointment information, whatever fourth dimension information supplied to it are ignored or normalized. This is obvious, when you lot impress values of both appointment classes, java.util.Date prints both appointment as well as fourth dimension component, piece SQL appointment prints solely information inwards dateformat yyyy-MM-dd. You tin likewise encounter telephone telephone to fourth dimension related methods from java.sql.Date e.g. getHours(), getMinutes() as well as getSeconds()  are failed past times throwing java.lang,.IllegalArgumentException. That's why its advised non transcend a SQL appointment to a method, which await a util appointment inwards Java.


/**  * Java Program to convert java.util.Date into java.sql.Date  * @author http://java67.blogspot.com  */ public class DateConverter {       public static void main(String args[]) {           // contains both appointment as well as fourth dimension information         java.util.Date utilDate = new java.util.Date();         System.out.println("Util appointment inwards Java : " + utilDate);           // contains solely appointment information without time         java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());         System.out.println("SQL appointment inwards Java : " + sqlDate);         System.out.printf("Time :  %s:%s:%s", sqlDate.getHours(), sqlDate.getMinutes(), sqlDate.getSeconds());       }   }   Output: Util appointment inwards Java : Monday February 03 13:26:05 PST 2014 SQL appointment inwards Java : 2014-02-03
Exception inwards thread "main" java.lang.IllegalArgumentException     at java.sql.Date.getHours(Date.java:182)

That's all nigh how to convert java.util.Date to java.sql.Date inwards Java. Always usage getTime() method to convert i appointment to other. Also scream back that sql appointment inwards Java solely holds appointment information without time. Though java.sql.Date is a subclass of java.util.Date it violates Liskov commutation principle, as well as tin non last passed where java.util.Date is expected. Compiler volition allow that exactly it volition neglect inwards runtime if you lot telephone telephone whatever fourth dimension related method, they are anyway deprecated, thus don't usage them.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

No comments:

Post a Comment