Java util date to sql date

You often need to convert java.util.Date to java.sql.Date if you are storing dates in 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 suppose 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 >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 JDBC driver could do the translation depending upon the data type of columns and Java developer could just pass the java.util.Date e.g. 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 >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:

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 which 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.

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 voilates 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:

Posted by: Theodora Fragkouli in Date October 21st, 2014 0 Views

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.

Run the example. The result is the one below:

I am trying to use a java.util.Date as input and then creating a query with it — so I need a java.sql.Date .

I was surprised to find that it couldn’t do the conversion implicitly or explicitly — but I don’t even know how I would do this, as the Java API is still fairly new to me.

18 Answers 18

How to convert java.util.Date to java.sql.Date?

Don’t. Both classes are outmoded.

  • Use java.time classes instead of legacy java.util.Date & java.sql.Date with JDBC 4.2 or later.
  • Convert to/from java.time if inter-operating with code not yet updated to java.time.
  • Instant instead of java.util.Date
    Both represent a moment in UTC. but now with nanoseconds instead of milliseconds.
  • LocalDate instead of java.sql.Date
    Both represent a date-only value without a time of day and without a time zone.

If you are trying to work with date-only values (no time-of-day, no time zone), use the LocalDate class rather than java.util.Date .

In Java 8 and later, the troublesome old date-time classes bundled with early versions of Java have been supplanted by the new java.time package. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

A SQL data type DATE is meant to be date-only, with no time-of-day and no time zone. Java never had precisely such a class† until java.time.LocalDate in Java 8. Let’s create such a value by getting today’s date according to a particular time zone (time zone is important in determining a date as a new day dawns earlier in Paris than in Montréal, for example).

At this point, we may be done. If your JDBC driver complies with JDBC 4.2 spec, you should be able to pass a LocalDate via setObject on a PreparedStatement to store into a SQL DATE field.

Likewise, use ResultSet::getObject to fetch from a SQL DATE column to a Java LocalDate object. Specifying the class in the second argument makes your code type-safe.

In other words, this entire Question is irrelevant under JDBC 4.2 or later.

If your JDBC driver does not perform in this manner, you need to fall back to converting to the java.sql types.

To convert, use new methods added to the old date-time classes. We can call java.sql.Date.valueOf(…) to convert a LocalDate .

And going the other direction.

While you should avoid using the old date-time classes, you may be forced to when working with existing code. If so, you can convert to/from java.time.

Go through the Instant class, which represents a moment on the timeline in UTC. An Instant is similar in idea to a java.util.Date . But note that Instant has a resolution up to nanoseconds while java.util.Date has only milliseconds resolution.

To convert, use new methods added to the old classes. For example, java.util.Date.from( Instant ) and java.util.Date::toInstant .

To determine a date, we need the context of a time zone. For any given moment, the date varies around the globe by time zone. Apply a ZoneId to get a ZonedDateTime .

† The java.sql.Date class pretends to be date-only without a time-of-day but actually does a time-of-day, adjusted to a midnight time. Confusing? Yes, the old date-time classes are a mess.

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Оцените статью
Много толка
Добавить комментарий