1. Introduction
In Java, we often need to convert a String to a Date object to perform various operations like comparing dates or storing them in a date type field in databases. The SimpleDateFormat class in Java provides a convenient way to achieve this.
2. Program Steps
1. Import necessary classes: import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;.
2. Define the date format in a string, for example, “dd-MM-yyyy”.
3. Create a SimpleDateFormat object with the date format string.
4. Use the parse method of SimpleDateFormat to convert the string to a Date object.
5. Catch any ParseException that may be thrown when the string is not in the expected format.
6. Print the converted Date object.
3. Code Program
// Step 1: Import necessary classes
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDate {
public static void main(String[] args) {
// Step 2: Define the date format in a string
String dateString = "31-12-2023";
// Step 3: Create a SimpleDateFormat object with the date format string
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
try {
// Step 4: Use the parse method of SimpleDateFormat to convert the string to a Date object
Date date = formatter.parse(dateString);
// Step 6: Print the converted Date object
System.out.println("Date converted from string: " + date);
} catch (ParseException e) { // Step 5: Catch any ParseException
e.printStackTrace();
}
}
}
Output:
Date converted from string: Sun Dec 31 00:00:00 UTC 2023
4. Step By Step Explanation
– Step 1: Necessary classes are imported for date parsing and formatting.
– Step 2: A string, dateString, is defined containing the date in "dd-MM-yyyy" format.
– Step 3: A SimpleDateFormat object, formatter, is created with the defined date format string.
– Step 4: The parse method of the SimpleDateFormat class is used to convert the dateString to a Date object.
– Step 5: Any ParseException thrown by the parse method is caught and its stack trace is printed.
– Step 6: The converted Date object is printed, showing Sun Dec 31 00:00:00 UTC 2023 as the output, representing the 31st of December, 2023.