java.lang.IllegalArgumentException when String to Date conversion in java


In this Example we are going to understandString to  Date conversions.

Error Message :
Exception in thread "main" java.lang.IllegalArgumentException
       at java.base/java.util.Date.parse(Date.java:616)
       at java.base/java.util.Date.<init>(Date.java:274)
       at com.si.ConvertDateToString.main(ConvertDateToString.java:13)

Error Description :


package com.si;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ConvertDateToString {

       public static void main(String[] args) throws ParseException {
             
              String date = "Wed Jul 2019 4:06:20";
              Date newDate = null;
              newDate = new Date(date);
              System.out.println(newDate);
             
       }

}

In the above example ,the red background color line is giving the exception.
There is no Date format to convert the String to date.

Solution:

To avoid this exception we need use the String used pattern in the String format..

package com.si;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ConvertDateToString {

       public static void main(String[] args) throws ParseException {
             
              String date = "Wed Jul 10 2019 4:06:20";
              Date newDate = null;
              DateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss");
              newDate = df.parse(date);
              System.out.println(newDate);
             
       }
}

                         
Output:

Wed Jul 10 04:06:20 IST 2019
Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar