I am trying to convert string to date using date format and used the following code but its shows an error.
public static Date ConvertStringtodate(String Date) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date Teststart = dateFormat.parse(Date);
return Teststart;
}
public static void main(String[]agrs) throws ParseException {
System.out.println(ConvertStringtodate("2022.02.10 17:54:55"));
}
Here is the error
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date at java.text.DateFormat.format(DateFormat.java:310) at java.text.Format.format(Format.java:157)
At the main method, you are sending date as 2022.02.10 17:54:55
. However, you wrote format of the pattern as yyyy-MM-dd hh:mm:ss
. Change the pattern at the SimpleDateFormat
constructor as yyyy.MM.dd HH:mm:ss
.