Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 543
Achilles Avatar asked Jan 11 '23 04:01

Achilles


1 Answers

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
like image 51
Kick Avatar answered Jan 17 '23 14:01

Kick