Nevermind....

public class MainClass {

  public static void main(String[] args) {
    java.util.Date utilDate = new java.util.Date();
    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    System.out.println("utilDate:" + utilDate);
    System.out.println("sqlDate:" + sqlDate);

  }

}

explains it. The link is http://www.java2s.com/Tutorial/Java/0040__Data-Type/ConvertfromajavautilDateObjecttoajavasqlDateObject.htm

Answer from David Ackerman on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › sql › Date.html
Date (Java Platform SE 8 )
October 20, 2025 - Java™ Platform Standard Ed. 8 ... A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value.
🌐
Baeldung
baeldung.com › home › java › java dates › java.util.date vs java.sql.date
java.util.Date vs java.sql.Date | Baeldung
January 8, 2024 - Its main purpose is to represent SQL DATE, which keeps years, months and days. No time data is kept. In fact, the date is stored as milliseconds since the 1st of January 1970 00:00:00 GMT and the time part is normalized, i.e. set to zero. Basically, it’s a wrapper around java.util.Date that handles SQL specific requirements.
Discussions

java.util.Date vs java.sql.Date - Stack Overflow
Additionally sql.Date isn't tied to timezones. java.sql.Time corresponds to SQL TIME and as should be obvious, only contains information about hour, minutes, seconds and milliseconds. More on stackoverflow.com
🌐 stackoverflow.com
jdbc - Get the current date in java.sql.Date format - Stack Overflow
I need to add the current date into a prepared statement of a JDBC call. I need to add the date in a format like yyyy/MM/dd. I've try with DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd... More on stackoverflow.com
🌐 stackoverflow.com
mysql - A datetime equivalent in java.sql ? (is there a java.sql.datetime ?) - Stack Overflow
Thanks, this is what I was looking for. How did you find out that these types match with certain SQL types? I am a bit troubled, since my query works fine with using NOW(), but not using a date instance of "now" in java and use it as a timestamp? More on stackoverflow.com
🌐 stackoverflow.com
Modern SQL has nice features that are not available through JPA. Blaze-Persistence provides mappings for them.
I personally hate ORMs that make you write queries in their special syntax that generate bad SQL (or SQL that would be written differently if written by hand). There is nothing hard about JDBC, especially now that we have try with resources. Having access to the full power of SQL (i.e. Recursive CTEs, ranking functions, etc.) is far more important than having an 'easy' API. For me Mybatis is a reasonable abstraction. More on reddit.com
🌐 r/java
41
102
September 11, 2020
Top answer
1 of 16
531

Nevermind....

public class MainClass {

  public static void main(String[] args) {
    java.util.Date utilDate = new java.util.Date();
    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    System.out.println("utilDate:" + utilDate);
    System.out.println("sqlDate:" + sqlDate);

  }

}

explains it. The link is http://www.java2s.com/Tutorial/Java/0040__Data-Type/ConvertfromajavautilDateObjecttoajavasqlDateObject.htm

2 of 16
137

tl;dr

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

Don’t.

Both Date classes are outmoded. Sun, Oracle, and the JCP community gave up on those legacy date-time classes years ago with the unanimous adoption of JSR 310 defining the java.time classes.

  • 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.
Legacy Modern Conversion
java.util.Date java.time.Instant java.util.Date.toInstant()
java.util.Date.from( Instant )
java.sql.Date java.time.LocalDate java.sql.Date.toLocalDate()
java.sql.Date.valueOf( LocalDate )

Example query with PreparedStatement.

myPreparedStatement.setObject( 
    … ,                                         // Specify the ordinal number of which argument in SQL statement.
    myJavaUtilDate.toInstant()                  // Convert from legacy class `java.util.Date` (a moment in UTC) to a modern `java.time.Instant` (a moment in UTC).
        .atZone( ZoneId.of( "Africa/Tunis" ) )  // Adjust from UTC to a particular time zone, to determine a date. Instantiating a `ZonedDateTime`.
        .toLocalDate()                          // Extract a date-only `java.time.LocalDate` object from the date-time `ZonedDateTime` object.
)

Replacements:

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

Details

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.

java.time

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

LocalDate todayLocalDate = LocalDate.now( ZoneId.of( "America/Montreal" ) );  // Use proper "continent/region" time zone names; never use 3-4 letter codes like "EST" or "IST".

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.

myPreparedStatement.setObject( 1 , localDate );

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.

LocalDate localDate = ResultSet.getObject( 1 , LocalDate.class );

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.

Convert to java.sql.Date

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

java.sql.Date sqlDate = java.sql.Date.valueOf( todayLocalDate );

And going the other direction.

LocalDate localDate = sqlDate.toLocalDate();

Converting from java.util.Date

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.

Instant instant = myUtilDate.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.

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
LocalDate localDate = zdt.toLocalDate();

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


About java.time

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.

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

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

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 brought some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android (26+) bundle implementations of the java.time classes.
    • For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
      • If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Top answer
1 of 7
634

Congratulations, you've hit my favorite pet peeve with JDBC: Date class handling.

Basically databases usually support at least three forms of datetime fields which are date, time and timestamp. Each of these have a corresponding class in JDBC and each of them extend java.util.Date. Quick semantics of each of these three are the following:

  • java.sql.Date corresponds to SQL DATE which means it stores years, months and days while hour, minute, second and millisecond are ignored. Additionally sql.Date isn't tied to timezones.
  • java.sql.Time corresponds to SQL TIME and as should be obvious, only contains information about hour, minutes, seconds and milliseconds.
  • java.sql.Timestamp corresponds to SQL TIMESTAMP which is exact date to the nanosecond (note that util.Date only supports milliseconds!) with customizable precision.

One of the most common bugs when using JDBC drivers in relation to these three types is that the types are handled incorrectly. This means that sql.Date is timezone specific, sql.Time contains current year, month and day et cetera et cetera.

Finally: Which one to use?

Depends on the SQL type of the field, really. PreparedStatement has setters for all three values, #setDate() being the one for sql.Date, #setTime() for sql.Time and #setTimestamp() for sql.Timestamp.

Do note that if you use ps.setObject(fieldIndex, utilDateObject); you can actually give a normal util.Date to most JDBC drivers which will happily devour it as if it was of the correct type but when you request the data afterwards, you may notice that you're actually missing stuff.

I'm really saying that none of the Dates should be used at all.

What I am saying that save the milliseconds/nanoseconds as plain longs and convert them to whatever objects you are using (obligatory joda-time plug). One hacky way which can be done is to store the date component as one long and time component as another, for example right now would be 20100221 and 154536123. These magic numbers can be used in SQL queries and will be portable from database to another and will let you avoid this part of JDBC/Java Date API:s entirely.

2 of 7
69

LATE EDIT: Starting with Java 8 you should use neither java.util.Date nor java.sql.Date if you can at all avoid it, and instead prefer using the java.time package (based on Joda) rather than anything else. If you're not on Java 8, here's the original response:


java.sql.Date - when you call methods/constructors of libraries that use it (like JDBC). Not otherwise. You don't want to introduce dependencies to the database libraries for applications/modules that don't explicitly deal with JDBC.

java.util.Date - when using libraries that use it. Otherwise, as little as possible, for several reasons:

  • It's mutable, which means you have to make a defensive copy of it every time you pass it to or return it from a method.

  • It doesn't handle dates very well, which backwards people like yours truly, think date handling classes should.

  • Now, because j.u.D doesn't do it's job very well, the ghastly Calendar classes were introduced. They are also mutable, and awful to work with, and should be avoided if you don't have any choice.

  • There are better alternatives, like the Joda Time API (which might even make it into Java 7 and become the new official date handling API - a quick search says it won't).

If you feel it's overkill to introduce a new dependency like Joda, longs aren't all that bad to use for timestamp fields in objects, although I myself usually wrap them in j.u.D when passing them around, for type safety and as documentation.

🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.sql › java › sql › Date.html
Date (Java SE 11 & JDK 11 )
January 20, 2026 - A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value.
🌐
Dariawan
dariawan.com › tutorials › java › java-sql-date-examples
java.sql.Date Examples | Dariawan
July 24, 2019 - Date(long date): Constructs a Date object using the given milliseconds time value. ... import java.sql.Date; public class SqlDateInitExample { public static void main(String[] args) { long now = System.currentTimeMillis(); Date sqlDate = new ...
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › java-sql-date-valueof-method-with-example
Java sql.Date valueOf() method with example
July 30, 2019 - The valueOf() method of the java.sql.Date class accepts a String value representing a date in JDBC escape format (yyyy-mm-dd) and converts · the given String value into Date object. Date date = Date.valueOf("date_string"); Let us create a table with name dispatches in MySQL database using CREATE statement as follows − ·
🌐
W3Schools
w3schools.com › java › java_date.asp
Java Date and Time
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
🌐
GitHub
github.com › frohoff › jdk8u-jdk › blob › master › src › share › classes › java › sql › Date.java
jdk8u-jdk/src/share/classes/java/sql/Date.java at master · frohoff/jdk8u-jdk
import java.time.LocalDate; · /** * <P>A thin wrapper around a millisecond value that allows · * JDBC to identify this as an SQL <code>DATE</code> value. A · * milliseconds value represents the number of milliseconds that · * have passed since January 1, 1970 00:00:00.000 GMT.
Author   frohoff
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.sql.date
Date Class (Java.Sql) | Microsoft Learn
A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. [Android.Runtime.Register("java/sql/Date", DoNotGenerateAcw=true)] public class Date : Java.Util.Date
🌐
GeeksforGeeks
geeksforgeeks.org › java › difference-between-java-sql-time-java-sql-timestamp-and-java-sql-date-in-java
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java - GeeksforGeeks
October 31, 2022 - Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e.
🌐
Quora
quora.com › How-do-I-convert-java-util-Date-into-java-sql-Date
How to convert java.util.Date into java.sql.Date - Quora
Answer (1 of 2): I hope this might help public class MainClass { public static void main(String[] args) { java.util.Date utilDate = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); System.out.println("utilDate:" + utilDate); System.out.print...
🌐
TutorialsPoint
tutorialspoint.com › how-do-i-create-a-java-sql-date-object-in-java
How do I create a java.sql.Date object in Java?
import java.sql.Date; public class Demo { public static void main(String args[]) { String str = "2017-12-03"; Date date = Date.valueOf(str); System.out.println("Date Value: "+date); } }
🌐
Dariawan
dariawan.com › tutorials › java › java-sql-date-java-sql-time-and-java-sql-timestamp
java.sql.Date, java.sql.Time, and java.sql.Timestamp | Dariawan
August 15, 2019 - Commands end with ; or \g. Your MySQL connection id is 9 Server version: 5.5.27 MySQL Community Server (GPL) mysql> connect coffeehouse Connection id: 10 Current database: coffeehouse mysql> select * from test_datetime; +------------+----------+---------------------+------------+----------+---------------------+ | dtm_date | dtm_time | dtm_timestamp | obj_date | obj_time | obj_timestamp | +------------+----------+---------------------+------------+----------+---------------------+ | 2019-08-15 | 15:48:19 | 2019-08-15 15:48:19 | 2019-08-15 | 15:48:19 | 2019-08-15 15:48:19 | +------------+----------+---------------------+------------+----------+---------------------+ 1 row in set (0.00 sec) Liked this Tutorial? Share it on Social media! ... This article is part of Java Date and Time Series.
🌐
Coderanch
coderanch.com › t › 368628 › java › convert-string-java-sql-Date
convert a string to java.sql.Date object (Java in General forum at Coderanch)
November 6, 2001 - You can get a Date back from the valueOf() method in java.sql.Date, but it requires "JDBC escape" format, i.e., yyyy-mm-dd. While we here, would you mind re-registering using the two name format spelled out in JavaRanch's namign policy? We're striving to make sure our site has the kind of appearance that corporate managers wouldn't mind seeing on their employee's monitors, and presenting a proper name helps us do that.
🌐
W3Schools
w3schools.com › sql › sql_dates.asp
Date Functions in SQL Server and MySQL
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
🌐
Oracle
docs.oracle.com › en › java › javase › 19 › docs › api › java.sql › java › sql › Date.html
Date (Java SE 19 & JDK 19)
December 12, 2022 - 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.
🌐
W3Schools
w3schools.com › sql › func_sqlserver_dateadd.asp
SQL Server DATEADD() Function
SELECT LastName, BirthDate, DATEADD(year, 18, BirthDate) AS DateAdd FROM Employees; Try it Yourself » ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial