Java
Date Format
String Manipulation
Programming
Coding Tips

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:

java
1import java.text.ParseException;
2import java.text.SimpleDateFormat;
3import java.util.Date;
4
5public class DateFormatExample {
6    public static void main(String[] args) {
7        String originalDateStr = "2023-03-01"; // Original date string
8        SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd");
9        SimpleDateFormat targetFormat = new SimpleDateFormat("dd/MM/yyyy");
10        
11        try {
12            Date date = originalFormat.parse(originalDateStr);
13            String reformattedStr = targetFormat.format(date);
14            System.out.println(reformattedStr); // Output: 01/03/2023
15        } catch (ParseException e) {
16            e.printStackTrace();
17        }
18    }
19}

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:

java
1import java.time.LocalDate;
2import java.time.format.DateTimeFormatter;
3
4public class DateTimeFormatterExample {
5    public static void main(String[] args) {
6        String originalDateStr = "2023-03-01"; // Original date string
7        DateTimeFormatter originalFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
8        DateTimeFormatter targetFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy");
9
10        LocalDate date = LocalDate.parse(originalDateStr, originalFormat);
11        String reformattedStr = date.format(targetFormat);
12        System.out.println(reformattedStr); // Output: 01/03/2023
13    }
14}

In this scenario, we use LocalDate to hold the date without time, which is often sufficient for date-only information.

Key Differences and Considerations

FeatureSimpleDateFormatDateTimeFormatter
Thread SafetyNot thread-safeThread-safe
Base Packagejava.textjava.time
API ModelMutableImmutable
Use with Java VersionsJava 7 and belowJava 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.


Course illustration
Course illustration

All Rights Reserved.