- java.util.Date vs java.sql.Date
- java.sql.Date
- How to Convert java.util.Date to java.sql.Date
- How to Convert java.sql.Date to java.util.Date
- Putting it All Together
- Conclusion
- Reference:
- How to Convert java.util.Date to java.sql.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
- Convert java.util Date to java.sql Date, Timestamp, and Time in Java
- 1. Convert java.util.Date to java.sql.Date
java.util.Date vs java.sql.Date
The java.util.Date represents a specific instant in time, with millisecond precision since the standard base time known as «the epoch», namely January 1, 1970, 00:00:00 GMT.
java.util.Date date = new java.util.Date(0L); System.out.println(date);
Thu Jan 01 07:30:00 SGT 1970
java.sql.Date
The java.sql.Date extends java.util.Date class, is a thin wrapper around a millisecond value (since the «epoch» -January 1, 1970, 00:00:00 GMT) to represent SQL DATE, which keeps years, months and days with no time data.
java.sql.Date sqlDate = new java.sql.Date(0L); System.out.println(sqlDate);
You only use java.sql.Date when working with JDBC and databases, like to set a date on a java.sql.PreparedStatement, get a date from a java.sql.ResultSet, etc.
How to Convert java.util.Date to java.sql.Date
java.util.Date to java.sql.Date conversion is necessary when a java.util.Date object needs to be written in a database which the column is used to store Date only, without time. Example of this date are birthdate, passport issue date, etc. java.sql.Date used by JDBC to identify an SQL DATE type.
import java.text.DateFormat; import java.text.SimpleDateFormat; public class UtilDateToSqlDateExample < public static void main(String[] args) < java.util.Date utilDate = new java.util.Date(); System.out.println("java.util.Date time: " + utilDate); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); System.out.println("java.sql.Date time : " + sqlDate); DateFormat df = new SimpleDateFormat("dd/MM/YYYY hh:mm:ss"); System.out.println("Date formatted : " + df.format(utilDate)); >>
java.util.Date time: Thu Aug 01 01:49:48 SGT 2019 java.sql.Date time : 2019-08-01 Date formatted : 01/08/2019 01:49:48
In the above example, we use getTime() method of java.util.Date to java.sql.Date constructor. The millisecond values wrapped by a java.sql.Date instance is ‘normalized’ by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated. And the result, as you can see, java.util.Date has both date and time information, but java.sql.Date only retain date information.
How to Convert java.sql.Date to java.util.Date
Vice versa, java.sql.Date to java.util.Date conversion is necessary when we need to read from database, and pass it to a java.util.Date variable.
import java.text.DateFormat; import java.text.SimpleDateFormat; public class SqlDateToUtilDateExample < public static void main(String[] args) < java.sql.Date sqlDate = java.sql.Date.valueOf("1980-04-09"); System.out.println("java.sql.Date time : " + sqlDate); java.util.Date utilDate = new java.util.Date(sqlDate.getTime()); System.out.println("java.util.Date time: " + utilDate); DateFormat df = new SimpleDateFormat("dd/MM/YYYY hh:mm:ss"); System.out.println("Date formatted : " + df.format(utilDate)); >>
java.sql.Date time : 1980-04-09 java.util.Date time: Wed Apr 09 00:00:00 SGT 1980 Date formatted : 09/04/1980 12:00:00
In above example, we set java.sql.Date to 9 April 1980. When we convert it to java.util.Date, the time component are set to 00:00:00.
Putting it All Together
In following example, we will implement what we have learn so far in a complete SQL INSERT example. First, we create a test table in our database. In this example, I’ll use PostgreSQL.
create table test_date ( curr_date date );
The following example demonstrates every step you need to insert the current date (get via new java.util.Date()) into the date field of an SQL database table.
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class SqlDateInsertExample < public static void main(String[] args) throws Exception < // (1) connect to postgresql database String url = "jdbc:postgresql://localhost/coffeeshop"; Class.forName("org.postgresql.Driver"); try (Connection conn = DriverManager.getConnection(url, "barista", "espresso")) < // (2) set java.sql.Date with current Date (and time) java.util.Date utilDate = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); // (3) insert java.sql.Date to DB String query = "INSERT INTO test_date(curr_date) VALUES (?)"; try (PreparedStatement pst = conn.prepareStatement(query)) < pst.setDate(1, sqlDate); // (4) execute update pst.executeUpdate(); >> > >
The example shows how to connect to a PostgreSQL database, construct a java.util.Date object, convert those java.util.Date object into a java.sql.Date object, create and use an SQL INSERT statement in a Java PreparedStatement, then execute this SQL INSERT statement. It resulted that our date is inserted into database. Let’s confirm that:
$ psql coffeeshop barista Password for user barista: psql (9.2.1) Type "help" for help. coffeeshop=> select * from test_date; curr_date ------------ 2019-08-01 (1 row)
Yes, it’s confirmed. The conversion and insertion worked as expected. Now, to read from database:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class SqlDateQueryExample < public static void main(String[] args) throws Exception < // (1) connect to postgresql database String url = "jdbc:postgresql://localhost/coffeeshop"; Class.forName("org.postgresql.Driver"); try (Connection conn = DriverManager.getConnection(url, "barista", "espresso")) < // (2) create statement and query Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT curr_date FROM test_date"); while ( rs.next() ) < java.sql.Date currSqlDate = rs.getDate("curr_date"); java.util.Date currDate = new java.util.Date(currSqlDate.getTime()); // (3) print java.util.Date result System.out.println(currDate); >> > >
Thu Aug 01 00:00:00 SGT 2019
The example above shows how to create and use an SQL QUERY statement in a Java Connection, get the result as java.sql.Date and convert it to java.util.Date.
Conclusion
java.sql.Date used in JDBC to store (and use to retrieve) a date only value. java.util.Date able to keeps both date and time, and used in general scenario, but considered as obsolete after Java 8. If you are using Java 8, then better to use new Date/Time API in java.time.* package.
Reference:
Liked this Tutorial? Share it on Social media!
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 — 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.
Convert java.util Date to java.sql Date, Timestamp, and Time in Java
This post will discuss how to convert java.util Date to java.sql Date, Timestamp, and Time in Java.
Prerequisite:
We know that Relational databases like Oracle, MySQL supports DATE, TIME, and TIMESTAMP data types. All these data types have a corresponding class in JDBC, and each of them extends java.util.Date . This post will discuss how to convert java.util Date to these classes:
1. Convert java.util.Date to java.sql.Date
Java has two Date classes, one present in the java.util package and the other present in the java.sql package. The java.sql.Date corresponds to SQL DATE containing the year, month, and day information while hour, minute, second, and millisecond information is not present.
The conversion from java.util.Date to java.sql.Date is actually very simple in Java. The Constructor of java.sql.Date expects milliseconds elapsed since Epoch (1 January 1970 00:00:00 GMT) which can be obtained by using getTime() method of java.util.Date object.
Output:
java.util.Date : Thu Jan 24 21:53:32 GMT 2015
java.sql.Date : 2015-01-24
Starting with Java 8, we should prefer using Instant class from java.time package which is similar to java.util Date class but it gives nanosecond accuracy. java.time.LocalDateTime (date-time without a time-zone), java.time.ZonedDateTime (date-time with a time-zone), LocalDate (date without a time-zone) and LocalTime (time without a time-zone) were also introduced in Java 8 and above.
Since SQL data type DATE is date-only, with no time and time-zone information, it is better to use java.time.LocalDate class rather than java.util.Date in Java 8 and above. We can create a LocalDate instance by getting today’s date according to a particular time zone.
Now to convert java.time.LocalDate to java.sql.Date , we can use valueOf() method, a recent addition in Java 8 and above, that can obtain an instance of java.sql.Date from a java.time.LocalDate object.