Java Code To Change Date Format
Chapter:
Date and Time
Last Updated:
15-08-2023 14:22:20 UTC
Program:
/* ............... START ............... */
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
String inputDateStr = "2023-08-15"; // Input date string
String inputFormatStr = "yyyy-MM-dd"; // Input date format
String outputFormatStr = "dd/MM/yyyy"; // Desired output date format
try {
SimpleDateFormat inputFormat = new SimpleDateFormat(inputFormatStr);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputFormatStr);
Date inputDate = inputFormat.parse(inputDateStr);
String outputDateStr = outputFormat.format(inputDate);
System.out.println("Input Date: " + inputDateStr);
System.out.println("Formatted Date: " + outputDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
/* ............... END ............... */
Output
Input Date: 2023-08-15
Formatted Date: 15/08/2023
In this output, you can see that the input date "2023-08-15" has been successfully parsed and
formatted into the desired output format "dd/MM/yyyy", resulting in "15/08/2023".
Notes:
-
In this example, the code takes an input date string in the format "yyyy-MM-dd" (e.g., "2023-08-15"), and it converts it to the desired output format "dd/MM/yyyy" (e.g., "15/08/2023"). The SimpleDateFormat class is used to parse the input date string and then format it into the desired output format.
Tags
Java code to change date format #How to change the format of a date in Java? #java date format dd/mm/yyyy #Java date format example