-1

I am using java to convert string to date but this exception occur. here is my program code:

 String[] split = invoice.split("-");
 String padded = null;
 SimpleDateFormat formatter = new SimpleDateFormat("YYYYMMDD");
 Date date = formatter.parse(split[0]);

here is the Exception:

  java.text.ParseException: Unparseable date: "20200302"
  • 3
    what is the string (input format for the date). can you provide the example. and use `yyyy-MM-dd` or `dd/MM/yyyy` – Silverfang Mar 02 '20 at 09:10
  • @Silverfang the input string is in the error message – Federico klez Culloca Mar 02 '20 at 09:12
  • 5
    You can't just make up formatting letters like `Y`, `M` and `D`. [They have meaning](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html). And don't use `SimpleDateFormat` and `Date`. Use `DateTimeFormatter` and `LocalDate` instead, which are much more modern. – Sweeper Mar 02 '20 at 09:12
  • Does this answer your question? [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion) – Nicktar Mar 02 '20 at 09:26

2 Answers2

0

try this::

    public static void main(String[] args) throws ParseException { 
    String invoice="20200302-ababab";
    String[] split =invoice.split("-");
     SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
     Date date =  formatter.parse(split[0]);

     System.out.println(date.toString());

}

output::

Mon Mar 02 00:00:00 IST 2020
0

If your date looks like "20200302" the formatter should look like:

SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

You can find more examles here.

Frank D.
  • 26
  • 4