In Java, to change the format of a date that is represented as a String
, you typically need to parse the original string into a Date
object (or LocalDate
, LocalDateTime
, etc.), and then format it into a new string with the desired format. You can use SimpleDateFormat
(for older versions of Java) or the DateTimeFormatter
(for Java 8 and newer) to accomplish this.
Using SimpleDateFormat
(Java 7 and earlier)
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
try {
// Original date string
String originalDateStr = "2025-01-20";
// Define the original format
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd");
// Parse the original string to a Date object
Date date = originalFormat.parse(originalDateStr);
// Define the new format
SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yyyy");
// Format the Date object into the new string format
String newDateStr = newFormat.format(date);
System.out.println("Original Date: " + originalDateStr);
System.out.println("New Date Format: " + newDateStr);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Original Date: 2025-01-20
New Date Format: 01/20/2025
In this example:
- We define the original date format (
yyyy-MM-dd
). - We parse the original string into a
Date
object. - We then format that
Date
object into a new string using a different format (MM/dd/yyyy
).
Using DateTimeFormatter
(Java 8 and newer)
For modern Java (Java 8 and later), you should use the DateTimeFormatter
class, which is part of the java.time
package.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Original date string
String originalDateStr = "2025-01-20";
// Define the original format
DateTimeFormatter originalFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Parse the string to a LocalDate object
LocalDate date = LocalDate.parse(originalDateStr, originalFormatter);
// Define the new format
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
// Format the LocalDate object into the new string format
String newDateStr = date.format(newFormatter);
System.out.println("Original Date: " + originalDateStr);
System.out.println("New Date Format: " + newDateStr);
}
}
Output:
Original Date: 2025-01-20
New Date Format: 01/20/2025
In this example:
- We define the original date format (
yyyy-MM-dd
) usingDateTimeFormatter
. - We parse the original string into a
LocalDate
object. - We then format the
LocalDate
object into a new string using a different format (MM/dd/yyyy
).