To convert a Java String to a Date object, you can use the SimpleDateFormat class. Here’s an example:
import java.text.SimpleDateFormat; import java.util.Date; public class StringToDateExample { public static void main(String[] args) { String dateString = "2023-05-07"; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = dateFormat.parse(dateString); } catch (Exception e) { e.printStackTrace(); } System.out.println("Date: " + date); } }
In this example, we create a SimpleDateFormat object with the pattern “yyyy-MM-dd”, which matches the format of the date string. We then call the parse method of the SimpleDateFormat object to convert the string to a Date object. Finally, we print out the Date object using the toString method.
Java String to Date Example:
Sure! Here’s an example Java program that demonstrates how to convert a String to a Date object using the SimpleDateFormat class:
import java.text.SimpleDateFormat; import java.util.Date; public class StringToDateExample { public static void main(String[] args) { String dateString = "2023-05-07"; // The input string to be converted SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // The format of the input string Date date = null; try { date = dateFormat.parse(dateString); // Parsing the input string to a Date object } catch (Exception e) { e.printStackTrace(); } System.out.println("Input String : " + dateString); System.out.println("Converted Date : " + date); } }
In this example, we create a SimpleDateFormat object with the format “yyyy-MM-dd”, which matches the format of the input String “2023-05-07”. We then call the parse method of the SimpleDateFormat object to convert the input String to a Date object.
Finally, we print out the input String and the converted Date object to the console. Note that we’ve included a try-catch block to handle any exceptions that might be thrown during the parsing process.