Convert Date Format Example in Java
Introduction
Convert Date Format is a classic Java console program that demonstrates the concept with complete source code and sample output. Conversion programs transform values between formats, units or representations.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Convert Date Format Example Program
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ConvertDateFormat{
public static void main(String[] args) {
try {
String datee = "21/08/2012";
System.out.println("The input date is:"+datee);
DateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date date = format1.parse(datee);
DateFormat format2 = new SimpleDateFormat("MM-dd-yyyy");
datee = format2.format(date);
System.out.println("Converted date is : " + datee);
}
catch (ParseException e) {
e.printStackTrace();
}
}
}Sample Output
The input date is:21/08/2012
Converted date is : 08-21-2012When to use
Use unit conversion programs when reading sensor data, building calculators, or localizing measurements for users.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.text.DateFormat;imports a class used later in the program. -
import java.text.ParseException;imports a class used later in the program. -
import java.text.SimpleDateFormat;imports a class used later in the program. -
import java.util.Date;imports a class used later in the program. -
String datee = "21/08/2012";updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below.