- java.util.Date to java.sql.Date
- How to Convert java.util.Date to java.sql.Date in Java?
- How to convert java.util.Date to java.sql.Date — JDBC Example
- Converting java.util.Date to java.sql.Date — Example
- Things to remember about SQL and Normal Date in Java
- How to Convert java.util.Date to java.sql.Date — Example
- Java Program to convert java.util.Date to java.sql.Date
java.util.Date to java.sql.Date
In this example, we shall show you how to convert a java.util.Date object to a java.sql.Date object. This conversion is usually necessary when a Date object needs to be written in a database.
java.util.Date represents a specific instant in time, with millisecond precision. It represents both date and time.
java.sql.Date is a wrapper around millisecond value and is used by JDBC to identify an SQL DATE type. It is a subclass of java.util.Date . Though, it only represents date information, so hours, minutes, seconds, and milliseconds must be set to zero in a specified time zone, so that this date is equivalent to an SQL DATE type.
In DatesConversion.java class below, we use the java.util.Date() constructor, that creates a Date object and initializes it to represent time to the nearest millisecond. This date is used in the convertUtilToSql(java.util.Date uDate) method to return a java.sql.Date object. In this method, the java.util.Date object is converted to a java.sql.Date object, using the java.sql.Date(long date) constructor. This constructor needs a long param, which is the time value in milliseconds. So, the getTime() API method of java.util.Date is used here that returns the number of milliseconds since January 1, 1970, 00:00:00 GMT of this date object.
So, this is it! The java.util.Date is converted to java.sql.Date.
package com.javacodegeeks.snippets.core; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * java.util.date to java.sql.date */ public class DatesConversion < public static void main(String[] args) < java.util.Date uDate = new java.util.Date(); System.out.println("Time in java.util.Date is : " + uDate); java.sql.Date sDate = convertUtilToSql(uDate); System.out.println("Time in java.sql.Date is : " + sDate); DateFormat df = new SimpleDateFormat("dd/MM/YYYY - hh:mm:ss"); System.out.println("Using a dateFormat date is : " + df.format(uDate)); >private static java.sql.Date convertUtilToSql(java.util.Date uDate) < java.sql.Date sDate = new java.sql.Date(uDate.getTime()); return sDate; >>
Run the example. The result is the one below:
Time in java.util.Date is : Tue Oct 21 00:21:54 EEST 2014 Time in java.sql.Date is : 2014-10-21 Using a dateFormat date is : 21/10/2014 - 12:21:54
As you can see, java.util.Date has both date and time information, whereas java.sql.Date only has date information.
This was an example of how to convert a java.util.Date object to a java.sql.Date object.
How to Convert java.util.Date to java.sql.Date in Java?
Date class is present in both java.util package and java.sql package. Though the name of the class is the same for both packages, their utilities are different. Date class of java.util package is required when data is required in a java application to do any computation or for other various things, while Date class of java.sql package is used whenever we need to store or read the data of DATE type in SQL, also Date class of java.sql package stores information only regarding the date, whereas Date class of java.util package stores both date and time information.
It must be remembered that when we need to convert one data form to another, we must use getTime() method of the Date class of java.util package.Though java.sql.Date class is a subclass of java.util.Date class, we can’t use java.sql.Date class wherever java.util.Date class must be passed, else it will violate the Liskov Substitution principle and our program will throw run time errors on execution, therefore it is not advised to pass SQL Date to methods that expect util date. Let us do discuss getTime() method prior to landing upon the implementation part.
The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by the Date object.
Parameters: The function does not accept any parameter.
Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM.
Exception: The function does not throw any exceptions.
How to convert java.util.Date to java.sql.Date — JDBC Example
You often need to convert java.util.Date to java.sql.Date if you are storing dates in a database e.g. SQL SERVER or MySQL. Since JDBC has their own data types for date and time e.g. java.sql.Date , java.sql.Time and java.sql.TimeStamp to match with database date, time and date-time types, you cannot pass a java.util.Date directly. All methods which are supposed to store dates e.g. setDate(paramName, paramValue) expects java.sql.Date, so it becomes essential to know how to convert java.util.Date to java.sql.Date in JDBC. You would be surprised to know that java.sql.Date is a subclass of java.util.Date and all it does is suppress or remove time-related fields from java.util.Date.
It is also a good example of a class which violates Liskov substitution principle, because even though java.sql.Date extends java.util.Date , you cannot pass around it to the method which expect java.util.Date because all time-related methods e.g. getHour() , getMinute() and getSeconds() method throws java.util.NotSupportedException .
I really hope that the JDBC driver could do the translation depending upon the data type of columns and Java developer could just pass the java.util.Date I mean, convert it to java.sql.Date if the column in the table is of type DATE, java.sql.Time if the type of column is TIME and java.sql.Timestamp if the data type of column is DATETIME.
Converting java.util.Date to java.sql.Date — Example
Unfortunately, there is no method like toSQLDate() in java.util.Date class to facilitate conversion between util date and SQL date but you can use getTime() method to extract long millisecond value from java.util.Date and create a new java.sql.Date based on that value as shown below:
Date now = new Date(); java.sql.Date sqlDate = new java.sql.Date(now.getTime());
This is the easiest and right way to convert a java.util.Date to java.sql.Date in Java. To learn more about JDBC and how to write Java application that connects to the database, please see Core Java, Volume II—Advanced Features (10th Edition), one of the best books to learn advanced features of Java programming language.
Things to remember about SQL and Normal Date in Java
1) java.sql.Date mapped to DATE datatype on JDBC i.e. Type.Date, which corresponds to date equivalent in DB side. In SQLSERVER till 2008 it maps to DATETIME and afterward maps to DATE data type.
2) java.sql.Date extends java.util.Date but violets Liskov Substituion Principle.
3) You can convert between java.util.Date and java.sql.Date by using getTime() method.
4) Here is mapping between MySQL date and time types and Java Date types:
That’s all about how to convert java.util.Date to java.sql.Date in Java and JDBC. It’s one of the most useful tips while working in JDBC. You can even create a class like JdbcUtil to host all date and time-related conversion methods like toSQLDate(), toSQLTime(), etc.
- 10 Examples of Java 8 Date and Time API (tutorial)
- How do you calculate the difference between two dates in Java? (solution)
- How to convert a String to Date in Java? (example)
- How to get a day, month, and year from a Date in Java? (solution)
- How to convert XMLGregorianCalendar to Date in Java? (solution)
- How to get the current date with Timezone in Java? (example)
- 3 ways to compare two dates in Java? (program)
- How to add days, months, and years from a Date in Java? (solution)
- The difference between java.sql.Time, java.sql.Timestamp and java.util.Date in Java? (answer)
- How to increment the date in Java? (solution)
- How to convert local time to GMT in Java? (answer)
- How to convert Date to String in Java? (answer)
- Why should you not use SimpleDateFormat in Java? (answer)
By the way, if you are using Java 8 then consider using LocalDate and LocalTime which are both immutable and thread-safe but yes again converting LocalDate to SQL Date or LocalTime to SQL date is not easy and I will show you how to do it on next article, till then keep learning.
How to Convert java.util.Date to java.sql.Date — Example
Hello guys, you may not know but there are two date classes in Java, one in java.util package and other in the java.sql package. Though both are known as Date class, there is some difference between java.util.Date and java.sql.Date e.g. Former is used whenever a Date is required in Java application while later is used to read and store DATE SQL type from the database. There is one more important difference is, java.util.Date stores both date and time values, while java.sql.date only stores date information, without any time part. As per Javadoc, java.sql.date is a thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. To conform with the definition of SQL DATE , the millisecond values wrapped by a java.sql.Date instance must be ‘normalized’ by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated. See SQL date vs Util date for few more differences.
In this Java tutorial, we will learn how to convert a java.util.Date to java.sql.Date , as we often need to do this when storing values into database. Since java.util.Date is standard way to represent date and time in Java, I only keep java.sql.Date up-to JDBC or DAO Layer, by the way if you need date with time, then use SQL TIMESTAMP type instead of DATE .
It’s also notable that java.sql.Date is subclass of java.util.Date, but it doesn’t mean you can pass around this in place of java.util.Date , because it violates Liskov Substitution principle.
All time related methods of java.sql.Date throws IllegalArgumentException , as 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 actually an interesting case of Inheritance, where superclass is more powerful than subclass, and instead of extending functionalities of parent class, subclass is actually limiting feature by not allowing time fields. If you have a code, which accepts java.util.Date , compiler will allow a java.sql.Date to be passed to that method, but as soon as you run the program, your code will fail with following error :
Exception in thread "main" java.lang.IllegalArgumentException at java.sql.Date.getHours(Date.java:182)
That’s why, make sure not to let java.sql.Date come outside of Data Access layer. By the way, because both the class has same name Date, you can not use them together by their simple name, you need to specify their fully quality name, i.e. name with package, as shown in below example. If we import java.util.Date then compiler will treat any Date as util date and not java.sql.Date .
Java Program to convert java.util.Date to java.sql.Date
Here is our sample program for converting a util date to sql date. Since both Date classes are based upon long time interval, you can easily convert them by passing value of getTime() , which represent milliseconds passed from 1st January 1970, also known as EPOCH. Since java.sql.Date only contains date information, any time information supplied to it are ignored or normalized.
This is obvious when you print values of both date classes, java.util.Date prints both date and time component, while SQL date prints only information in dateformat yyyy-MM-dd .
You can also call to time-related methods from java.sql.Date e.g. getHours() , getMinutes() and getSeconds() are failed by throwing java.lang,.IllegalArgumentException. That’s why it’s advised not to pass a SQL date to a method, which expect a util date in 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 date and time information java.util.Date utilDate = new java.util.Date(); System.out.println("Util date in Java : " + utilDate); // contains only date information without time java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); System.out.println("SQL date in Java : " + sqlDate); System.out.printf("Time : %s:%s:%s", sqlDate.getHours(), sqlDate.getMinutes(), sqlDate.getSeconds()); > > Output: Util date in Java : Mon Feb 03 13:26:05 PST 2014 SQL date in Java : 2014-02-03
Exception in thread "main" java.lang.IllegalArgumentException at java.sql.Date.getHours(Date.java:182)
That’s all about how to convert java.util.Date to java.sql.Date in Java. Always use getTime() method to convert one date to other. Also remember that sql date in Java only holds date information without time. Though java.sql.Date is a subclass of java.util.Date it violates Liskov substitution principle, and can not be passed where java.util.Date is expected. Compiler will allow that but it will fail in runtime if you call any time related method, they are anyway deprecated, so don’t use them.