java.text.ParseException while converting String to Date in java

In this Example we are going to understand the exceptions while
converting String to Date format.

Error Message :
Wed Jul 10 12:45:25 IST 2019
Exception in thread "main" java.text.ParseException: Unparseable date:
"2019-07-10 12:23:37"
at java.base/java.text.DateFormat.parse(DateFormat.java:395)
at com.si.Convertion.main(Convertion.java:20)

Error Description :


package com.si;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Formatter;


public class Convertion {

public static void main(String[] args) throws ParseException {

Date currentDate = Calendar.getInstance().getTime();
System.out.println(currentDate);

String date = "2019-07-10 12:23:37";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy'T' HH:mm:ss");

Date parseDate = format.parse(date);
long time = parseDate.getTime();
System.out.println(time);

}

}

In the above example ,the red background color line is giving the exception.
The String we have given and the String formatter specified pattern is
not matching.
Due to this mismatch we are getting parse exception.

Solution:

To avoid this exception we need follow same pattern in String given
format and the String formatter pattern.

package com.si;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Formatter;


public class Convertion {

public static void main(String[] args) throws ParseException {

Date currentDate = Calendar.getInstance().getTime();
System.out.println(currentDate);

String date = "2019-07-10 12:23:37";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date parseDate = format.parse(date);
long time = parseDate.getTime();
System.out.println(time);

}

}


Output:
Wed Jul 10 12:43:34 IST 2019
1487507017000
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