简体   繁体   中英

Format String Date from dd-MM-YYYY (Unparseable date)

I have a problem here, the format of the date was given (dd-MM-YYYY) and it's a not a good format (I know) but that was the raw data, and I can't parse the string using SimpleDateFormat class, it gives an Error

java.text.ParseException: Unparseable date: "27-08-2019"

And I also use the DateTimeFormatter but again it can't be parse, this is the error.

java.time.format.DateTimeParseException: Text '19-08-2019' could not be parsed at index 0

So my working option is to format first the String so that the Date Formatter can parse the string date, but if there are other option to minimize manipulation of data in String format will be nice. Thanks.

EDIT

Sorry for not posting the code. This the code using the SimpleDateFormat

String string = "08-27-2019";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date);

And here using the DateTimeFormatter and LocalDate .

String string = "08-27-2019";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);

Thanks for all the people help me, I got it working after pointing out my mistakes. I just parse it with the format given then format the parse Date to the format I want to have.

        String string = "27-08-2019";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(string, formatter);
        System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(date));

If there are more pointers to my solution I'm gladly accept any correction. Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM