Java SimpleDateFormat Cannot format given Object as a Date

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( at

>Solution :

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". If you change string at main as "2022-02-10 17:54:55" or you can change the pattern at the SimpleDateFormat constructor as "yyyy.MM.dd HH:mm:ss".

Leave a Reply