Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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(DateFormat.java:310) at
java.text.Format.format(Format.java:157)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading