eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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(); 
System.out.println(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); 
System.out.println(date);
// 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");
isoFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));

java.util.Date date = isoFormat.parse("2010-05-23T22:01:02");
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
System.out.println(sqlDate);
// This will print 2010-05-23

TimeZone.setDefault(TimeZone.getTimeZone("Rome"));
sqlDate = new java.sql.Date(date.getTime());
System.out.println(sqlDate);
// 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");
isoFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
Date date = isoFormat.parse("2010-05-23T22:01:02");

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

TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
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:

TimeZone.setDefault(TimeZone.getTimeZone("Rome"));
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. A Word About “Converting” java.sql.Date to java.util.Date

We’ve learned how to convert java.util.Date to java.sql.Date. Sometimes, we only have a java.sql.Date or java.sql.Timestamp instance, but we want to convert it to a java.util.Date.

Actually, we don’t need to convert a java.sql.Date to a java.util.Date. This is because, both java.sql.Date and java.sql.Timestamp are subclasses of java.util.Date. Therefore, a java.sql.Date or java.sql.Timestamp is a java.util.Date.

Next, let’s verify this in a test:

java.util.Date date = UtilToSqlDateUtils.createAmericanDate("2010-05-23T00:00:00");
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
Assertions.assertEquals(date, sqlDate);

java.util.Date dateWithTime = UtilToSqlDateUtils.createAmericanDate("2010-05-23T23:59:59");
java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(dateWithTime.getTime());
Assertions.assertEquals(dateWithTime, sqlTimestamp);

However, there are some situations that we want to create a new java.util.Date object from a given java.sqlDate or java.sql.Timestamp instance. To achieve that, we can utilize the getTime() method of the java.sql.Date or java.sql.Timestamp class to create a new java.util.Date object:

java.util.Date date = UtilToSqlDateUtils.createAmericanDate("2010-05-23T00:00:00");
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
java.util.Date newDate = new Date(sqlDate.getTime());
Assertions.assertEquals(date, newDate);

java.util.Date dateWithTime = UtilToSqlDateUtils.createAmericanDate("2010-05-23T23:59:59");
java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(dateWithTime.getTime());
java.util.Date newDateWithTime = new Date(sqlTimestamp.getTime());
Assertions.assertEquals(dateWithTime, newDateWithTime);

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

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)