In the following code snippet we will see hot to change a date from one format to another format. For example from 2024-11-04
to 04-Nov-24
format in Java. We can use the DateTimeFormatter
class from the java.time.format
package to do the conversion.
The steps are:
- Parse the original date string.
- Format it to the desired pattern.
Here’s the complete code to do this:
package org.kodejava.datetime;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateFormatConversion {
public static void main(String[] args) {
// The original date string
String originalDate = "2024-11-04";
// Define the input and output date formats
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MMM-yy");
// Parse the original date
LocalDate date = LocalDate.parse(originalDate, inputFormatter);
// Format the date to the desired pattern
String formattedDate = date.format(outputFormatter);
// Print the formatted date
System.out.println(formattedDate);
}
}
Output:
04-Nov-24
In the code above we define two formatters, one for the original date format, and the second one is for the new date format. The input formatter matches the original date format (yyyy-MM-dd
). The output formatter specifies the desired format (dd-MMM-yy
).
We use the LocalDate.parse()
method to parse the string of original date into a LocalDate
object. Next, we use the LocalDate.format()
method to convert into a new date format using the defined formatter object.
This approach uses java.time
API introduced in Java 8, which is the recommended way to handle date and time in Java due to its immutability and thread-safety features.