Convert java.util.Date to String

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

1. Overview

In this tutorial, we’ll show how we can convert Date objects to String objects in Java. To do so, we’ll work with the older java.util.Date type as well as with the new Date/Time API introduced in Java 8.

If you’d like to learn how to do the opposite conversion, i.e., from String to Date types, you can check out this tutorial here.

We’ve set default TimeZone to CET to prevent issues when working with the new API later. We should note that the Date itself doesn’t have any time zone, but its toString() uses the current default time zone.

We’ll be using this Date instance in all of our examples below.

2.2. Using the SimpleDateFormat Class

We’ll make use of the format() method of the SimpleDateFormatclass in this example. Let’s create an instance of it by using our date format:

DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);

After this, we can format our date and compare it with the expected output:

With this approach, we are passing style patterns — MEDIUM for the date and SHORT for the time in our case.

3. Using the Formatter Class

Another simple way of getting the same String as in earlier examples is to use the Formatter class.

While this may not be the most readable solution, it is a thread-safe one-liner that could be useful, especially in a multi-threaded environment (we should keep in mind that SimpleDateFormat is not thread-safe):

We used 1$ to indicate that we’ll be passing only one argument to be used with every flag. A detailed explanation of the flags could be found on Date/Time Conversions part of the Formatter class.

4. Converting Using Java 8 Date/Time API

The Date/Time API from Java 8 is far more powerful than the java.util.Date and java.util.Calendar classes, and we should use it whenever possible. Let’s see how we can put it to use to convert our existing Date object to String.

This time, we’ll use the DateTimeFormatterclass and its format() method, as well as the same date pattern, declared in Section 2.1:

5. Conclusion

In this article, we illustrated several ways of converting java.util.Date objects to String. We first showed how to do that using the older java.util.Date and java.util.Calendar classes and corresponding date formatting classes.

Then we used the Formatter class and, finally, the Java 8 Date/Time API.