Change date format in a Java string
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In Java, handling date and time is a common task in many applications. However, formatting dates can be challenging due to different date notation standards worldwide. In this article, we'll discuss how to change the date format in a Java string using both old and new date-time APIs.
Using SimpleDateFormat (Java 7 and before)
Before Java 8, SimpleDateFormat was commonly used for formatting and parsing date strings. It belongs to the java.text package and is both simple to use and flexible, provided you handle its limitations carefully.
Here's how to use SimpleDateFormat to change the date format:
In this example, we first parse the originalDateStr into a Date object and then format it into the desired new format.
Using DateTimeFormatter (Java 8+)
Java 8 introduced a new API for date and time manipulation under the java.time package, which is more robust and thread-safe. DateTimeFormatter is part of this new package and is used for formatting and parsing date-time objects.
Here’s how you can change the date format using DateTimeFormatter:
In this scenario, we use LocalDate to hold the date without time, which is often sufficient for date-only information.
Key Differences and Considerations
| Feature | SimpleDateFormat | DateTimeFormatter |
| Thread Safety | Not thread-safe | Thread-safe |
| Base Package | java.text | java.time |
| API Model | Mutable | Immutable |
| Use with Java Versions | Java 7 and below | Java 8 and above |
Additional Techniques and Tools
Locale-Specific Formatting
Both formatters support locale-sensitive patterns. When dealing with international applications, leveraging the Locale class ensures that dates are formatted in a way that is familiar to the user's region.
Formatting Time Zones
Working with time zones? ZonedDateTime from the Java 8+ java.time package allows you to handle date-time values in specific time zones, which can be formatted using DateTimeFormatter.
Parsing Leniency
Both formatters allow you to control the leniency of the parsing. By default, SimpleDateFormat is lenient, whereas DateTimeFormatter is strict. This means that invalid date strings that do not match the format pattern might still be parsed without an error in SimpleDateFormat, which can lead to unexpected results.
Conclusion
Converting between different date formats in Java strings necessitates careful selection between Java's older and newer date-time APIs. For most new projects, DateTimeFormatter with its thread-safe and immutable design is preferred over SimpleDateFormat. However, understanding both is essential for maintaining and upgrading legacy systems or when working in environments pre-Java 8.

