Unparseable date exception when converting a string to "yyyy-MM-dd HH:mm:ss"

21,289

The date in string is in yyyyMMdd format and want to convert it into yyyy-MM-dd HH:mm:ss so use below code :

        DateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
        DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = originalFormat.parse("19611015");
        String formattedDate = targetFormat.format(date); 
        System.out.println(formattedDate);

Output :

1961-10-15 00:00:00
Share:
21,289

Related videos on Youtube

Achilles
Author by

Achilles

merge keep

Updated on July 09, 2022

Comments

  • Achilles
    Achilles almost 2 years

    Hi I am trying to convert a string 19611015 to a date formate of ("yyyy-MM-dd HH:mm:ss") before storing it into a sybase database table. I have tried the below code which gives me the error:

    Unparseable date: "19611015"

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println(formatter.parse("19611015"));
    

    I have been reading some long and complex solutions to this, some suggesting to use Locale. Could someone explain maybe an alternative simple solution to convert string I have to a date format I am after above. Thank you.

    • Alexis C.
      Alexis C. over 10 years
      19611015 is not in the format yyyy-MM-dd HH:mm:ss
    • Kick
      Kick over 10 years
      19611015 is in which format ??
  • Alexis C.
    Alexis C. over 10 years
    19611015 became 1969-12-10 15:46:18?
  • Nikhil Joshi
    Nikhil Joshi over 10 years
    Hello ZouZou, I am converting long value to MS and then parsing. Please let me know if this is incorrect.
  • Alexis C.
    Alexis C. over 10 years
    IMHO, 19611015 means 1961-10-15. And 19611015 * 1000 overflows.
  • Nikhil Joshi
    Nikhil Joshi over 10 years
    Opps, I thought 19611015 is MilliSecond, my bad.
  • Alexis C.
    Alexis C. over 10 years
    Even if it was, your code won't work since 19611015 * 1000 overflows.