Java util date to String Conversion
In this tutorial will see how to convert date object to string objects in java. To convert it, there are few ways to implement it. Using java.util.Date and Using java 8 time and date APIs.
Converting a java.util.Date object into a formatted String representation is a core task in Java, primarily handled by the java.text.SimpleDateFormat class. This process involves defining a specific pattern (the format) and then applying that pattern to the Date object.
The Standard Approach: SimpleDateFormat
The SimpleDateFormat class, found in the java.text package, is the standard tool for formatting dates in a locale-sensitive manner.
1. Key Steps in the Process
- Instantiate
SimpleDateFormat: Create an instance of the class, passing the desired date and time pattern as a String argument. - Call
format(): Use theformat(Date date)method on theSimpleDateFormatobject. This method takes yourDateobject and returns the formattedString.
2. Formatting Pattern Symbols
The pattern String dictates the exact layout of the output. Here are the most common symbols used:
| Symbol | Meaning | Example |
y | Year | yyyy $\rightarrow$ 2025 |
M | Month in year | MM $\rightarrow$ 11; MMM $\rightarrow$ Nov; MMMM $\rightarrow$ November |
d | Day in month | dd $\rightarrow$ 22 |
H | Hour in 24-hour format (0-23) | HH $\rightarrow$ 20 |
h | Hour in 12-hour format (1-12) | h $\rightarrow$ 8 |
m | Minute in hour | mm $\rightarrow$ 57 |
s | Second in minute | ss $\rightarrow$ 26 |
a | AM/PM marker | a $\rightarrow$ PM |
z | Time Zone | z $\rightarrow$ IST |
3. Code Example
Java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateToStringConverter {
public static void main(String[] args) {
// 1. Get the current Date object
Date currentDate = new Date();
// Define a custom pattern: Year-Month-Day Hour:Minute:Second AM/PM
String pattern = "yyyy-MM-dd hh:mm:ss a";
// 2. Instantiate SimpleDateFormat with the pattern
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
// 3. Apply the format to the Date object
String formattedString = formatter.format(currentDate);
System.out.println("Original Date: " + currentDate.toString());
System.out.println("Formatted String: " + formattedString);
// Example with Locale (e.g., French month names)
SimpleDateFormat frenchFormatter = new SimpleDateFormat("dd MMMM yyyy", Locale.FRENCH);
String frenchDate = frenchFormatter.format(currentDate);
System.out.println("French Format: " + frenchDate);
}
}
Modern Approach (Java 8 and Later)
While SimpleDateFormat works, it has known issues, particularly that it is not thread-safe, meaning the same formatter instance should not be used concurrently by multiple threads.
Java 8 introduced the java.time API, which includes the LocalDateTime, ZonedDateTime, and DateTimeFormatter classes that are immutable and thread-safe.
If you are working with modern Java, the recommended practice is to first convert the legacy java.util.Date to the modern API, and then format it.
1. Conversion to Modern API
A java.util.Date object represents an instant on the timeline. We convert it to an Instant and then map it to a specific time zone to get a ZonedDateTime.
Java
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class Java8Converter {
public static void main(String[] args) {
Date legacyDate = new Date();
// 1. Convert legacy Date to ZonedDateTime
ZonedDateTime zdt = legacyDate.toInstant()
.atZone(ZoneId.systemDefault());
// 2. Define the thread-safe formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
// 3. Apply the format
String formattedString = zdt.format(formatter);
System.out.println("Java 8 Formatted String: " + formattedString);
}
}
2. Key Advantages of DateTimeFormatter
- Thread Safety: The core benefit is that
DateTimeFormatterinstances can be shared safely across your entire application. - Built-in Styles: It offers predefined, localized format styles (e.g.,
DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)) that automatically adapt to the user’s locale without manual pattern definition. - Clarity: The separation of the date/time object (
ZonedDateTime) from the formatter (DateTimeFormatter) leads to cleaner code.
Let’s see how to convert date to string in java
java.util.Date to String
First, we need to define the pattern we need to convert it to.
package com.slb.core.java;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DateFormatter {
private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a";
private static final String EXPECTED_DATE_STRING_FORMAT = "Mar 1, 2018 12:00 PM";
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("IST"));
Calendar calendar = Calendar.getInstance();
calendar.set(2018, Calendar.MARCH, 1, 12, 0);
Date date = calendar.getTime();
DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
String formattedDate = formatter.format(date);
assertEquals(EXPECTED_DATE_STRING_FORMAT , formattedDate);
System.out.println(formattedDate);
}
}
In the above code snippet, we are using simpleDateFormatter to format the date.
O/P
Mar 1, 2018 12:00 PM
Process finished with exit code 0
Converting Using Java 8 Date/Time API
Let’s see how to convert string to java util date in java 8. We will make java 8’s date and time API to format the date. Checkout JAVA8 tutorials here.
package com.slb.core.java;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DateFormatter {
private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a";
private static final String EXPECTED_DATE_STRING_FORMAT = "Mar 1, 2023 12:00 PM";
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("IST"));
Calendar calendar = Calendar.getInstance();
calendar.set(2023, Calendar.MARCH, 1, 12, 0);
Date date = calendar.getTime();
DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
String formattedDate = formatter.format(date);
assertEquals(EXPECTED_DATE_STRING_FORMAT , formattedDate);
System.out.println(formattedDate);
//using java 8
DateTimeFormatter formatterJava8Example = DateTimeFormatter.ofPattern(DATE_FORMAT);
Instant instant = date.toInstant();
LocalDateTime localDateTime = instant.atZone(ZoneId.of("UTC"))
.toLocalDateTime();
String formattedDateJava8 = localDateTime.format(formatterJava8Example);
System.out.println(formattedDateJava8);
}
}
O/P
Mar 1, 2023 12:00 PM
Mar 1, 2023 06:30 AM
Process finished with exit code 0
FAQ
Java java.util.Date to String Conversion FAQs
These FAQs address common issues and best practices related to formatting date objects in Java, focusing on the transition from the legacy java.util.Date and SimpleDateFormat to the modern java.time API.
1. What is the single biggest problem with using SimpleDateFormat?
The major issue is that java.text.SimpleDateFormat is not thread-safe.
If multiple threads try to use the same SimpleDateFormat instance concurrently (e.g., in a web server or multi-threaded application) to format or parse dates, it can lead to corrupted output, incorrect results, or unexpected exceptions. This requires developers to either create a new instance for every use or manage thread-local instances, adding significant boilerplate.
2. Why is the Java 8 DateTimeFormatter approach recommended over SimpleDateFormat?
The modern approach, utilizing java.time.format.DateTimeFormatter, is strongly recommended because it is immutable and thread-safe.
You can safely define a single DateTimeFormatter instance once and share it across all threads in your application. Additionally, the java.time API offers clearer distinction between date, time, and timezone objects (LocalDate, LocalTime, ZonedDateTime), eliminating many of the subtle bugs inherent in the legacy Date and Calendar classes.
3. How does the conversion process handle Time Zones?
This is a critical distinction between the two APIs:
| Aspect | Legacy (SimpleDateFormat) | Modern (DateTimeFormatter) |
Date Object | java.util.Date has no concept of time zone. It represents a single moment in time (like UTC). | ZonedDateTime holds the time, date, and time zone information explicitly. |
| Formatting | The SimpleDateFormat formatter defaults to the JVM’s default time zone unless explicitly set using setTimeZone(). | The DateTimeFormatter formats the date based on the time zone contained within the ZonedDateTime object it is given. |
When converting a java.util.Date to a formatted String, you must be aware that the output time will reflect the timezone setting of the formatter or the machine itself.
4. How can I change the language (locale) of the formatted String?
Locale determines things like month names (e.g., “Nov” vs. “Noviembre”) and time separators.
- Legacy: Pass a
Localeobject when instantiating the formatter:Javanew SimpleDateFormat("dd MMMM yyyy", Locale.FRENCH); - Modern: Use the
withLocale()method on aDateTimeFormatterinstance:JavaDateTimeFormatter.ofPattern("dd MMMM yyyy").withLocale(Locale.FRENCH);
5. Can I convert a String back into a Date object using the formatter?
Yes. Both the legacy and modern formatters are designed for two-way conversion:
- Formatting (Date $\rightarrow$ String): Use the
format()method. - Parsing (String $\rightarrow$ Date): Use the
parse()method.
When parsing, the format string you use must exactly match the pattern of the input string, or it will throw a ParseException (legacy) or a DateTimeParseException (modern).
Checkout the complete example here at githib@SLB

For over 15 years, I have worked as a hands-on Java Architect and Senior Engineer, specializing in building and scaling high-performance, enterprise-level applications. My career has been focused primarily within the FinTech, Telecommunications, or E-commerce sector, where I’ve led teams in designing systems that handle millions of transactions per day.
Checkout my profile here : AUTHOR https://simplifiedlearningblog.com/author/