9.How to convert String to Date.
💡Code:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class StringToDateConversion7078 { public static void main(String[] args) { // Example string representing a date String dateString = "2023-11-10"; // Convert the string to a Date Date convertedDate = convertStringToDate(dateString); // Print the converted Date System.out.println("Converted Date: " + convertedDate); } // Function to convert a String to a Date private static Date convertStringToDate(String dateString) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { // Use the parse method to convert the String to a Date return dateFormat.parse(dateString); } catch (ParseException e) { // Handle the case when the string is not a valid date System.err.println("Error: " + e.getMessage()); return null; // You can choose a default value or handle it differently based on your requirement } } }
📸Output :
.png)