Java Program To Convert String To Date Object
Chapter:
Miscellaneous
Last Updated:
11-08-2023 17:06:15 UTC
Program:
/* ............... START ............... */
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateExample {
public static void main(String[] args) {
// Input string representing the date
String dateString = "2023-08-11";
// Define the date format to match the input string
String dateFormat = "yyyy-MM-dd";
// Create a SimpleDateFormat object
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
try {
// Parse the input string and convert it to a Date object
Date date = sdf.parse(dateString);
// Print the converted Date object
System.out.println("Converted Date: " + date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
/* ............... END ............... */
Output
Converted Date: Thu Aug 11 00:00:00 UTC 2023
Notes:
-
In this example, the input string "2023-08-11" is converted to a Date object using the specified date format "yyyy-MM-dd". The SimpleDateFormat class is used to parse the input string and create a Date object. The parse method can throw a ParseException if the input string doesn't match the specified format, so make sure to handle that exception appropriately in your code.