Partner – DBSchema – NPI (tag = SQL)
announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Course – LS (cat=Java)

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Introduction

In this short tutorial, we will explore several strategies for converting a java.util.Date to a java.sql.Date.

First, we’ll take a look at the standard conversion, and then, we’ll check some alternatives that are considered best practices.

2. java.util.Date vs java.sql.Date

Both these date classes are used for specific scenarios and are part of different Java standard packages:

  • The java.util package is part of the JDK and contains various utility classes together with the date and time facilities.
  • The java.sql package is part of the JDBC API, which is included by default in the JDK starting from Java 7.

java.util.Date represents a specific instant in time, with millisecond precision:

java.util.Date date = new java.util.Date(); 
// Wed Mar 27 08:22:02 IST 2015

java.sql.Date is a thin wrapper around a millisecond value that allows JDBC drivers to identify this as an SQL DATE value. The value of this class is nothing more than the year, month, and day of a specific date calculated as milliseconds starting from the Unix epoch. Any time information more granular than the day will be truncated:

long millis=System.currentTimeMillis(); 
java.sql.Date date = new java.sql.Date(millis); 
// 2015-03-30

3. Why Conversion Is Needed

While java.util.Date usage is more general, java.sql.Date is used to enable communication of a Java application with a database. Thus, the conversion to a java.sql.Date is required in these cases.

Explicit reference casting won’t work either because we’re dealing with a completely different class hierarchy: No downcasting or upcasting is available. If we attempt to cast one of these dates to the other, we’ll receive a ClassCastException:

java.sql.Date date = (java.sql.Date) new java.util.Date() // not allowed

4. How to Convert to java.sql.Date

There are several strategies to convert from a java.util.Date to a java.sql.Date that we will explore below.

4.1. Standard Conversion

As we saw above, java.util.Date contains time information and java.sql.Date does not. We thus achieve a lossy conversion by using the constructor method of java.sql.Date, which takes in the input time represented in milliseconds starting from the Unix epoch:

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

In fact, losing the time portion of a represented value may result in a different date being reported due to different time zones:

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

java.util.Date date = isoFormat.parse("2010-05-23T22:01:02");
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
// This will print 2010-05-23

sqlDate = new java.sql.Date(date.getTime());
// This will print 2010-05-24

For this reason, we might want to consider one of the conversion alternatives that we’ll examine in the next subsections.

4.2. Using java.sql.Timestamp Instead of java.sql.Date

The first alternative to consider is to use the java.sql.Timestamp class instead of java.sql.Date. This class contains information about time as well:

java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
System.out.println(date); //Mon May 24 07:01:02 CEST 2010
System.out.println(timestamp); //2010-05-24 07:01:02.0

Of course, if we query a database column that has a DATE type, this solution may not be the right one.

4.3. Using Classes From the java.time Package

The second and best alternative is to convert both classes to new ones provided in the java.time package. The only prerequisite for this conversion is to be using JDBC 4.2 (or later). JDBC 4.2 was released with Java SE 8 in March 2014.

Starting from Java 8, the usage of date-time classes provided in the early versions of Java has been discouraged in favor of the ones provided in the new java.time package. These enhanced classes work better for all date/time needs, including communication with databases through JDBC drivers.

If we adopt this strategy, java.util.Date should be converted to java.time.Instant:

Date date = new java.util.Date();
Instant instant = date.toInstant().atZone(ZoneId.of("Rome");

And java.sql.Date should be converted to java.time.LocalDate:

java.sql.Date sqlDate = new java.sql.Date(timeInMillis);
java.time.LocalDate localDate = sqlDate.toLocalDate();

The java.time.Instant class can be used to map SQL DATETIME columns, and java.time.LocalDate can be used to map SQL DATE columns.

As an example, let’s now generate a java.util.Date with timezone information:

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = isoFormat.parse("2010-05-23T22:01:02");

Next, let’s generate a LocalDate from the java.util.Date:

java.time.LocalDate localDate = date.toInstant().atZone(ZoneId.of("America/Los_Angeles")).toLocalDate();
Asserts.assertEqual("2010-05-23", localDate.toString());

If we then try to switch the default time zone, the LocalDate will keep the same value:

localDate = date.toInstant().atZone(ZoneId.of("America/Los_Angeles")).toLocalDate();
Asserts.assertEqual("2010-05-23", localDate.toString())

This works as expected, thanks to the explicit reference we made specifying the time zone during the conversion.

5. Conclusion

In this tutorial. we’ve seen how it’s possible to convert from the standard java.util Date to the one provided in the java.sql package. Together with the standard conversion, we’ve examined two alternatives. The first uses Timestamp, and the second relies on newer java.time classes.

As always, the full source code of the article is available over on GitHub.

Course – LS (cat=Java)

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!