Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

java - Error: Text '1/31/2020' could not be parsed at index 0 while trying to parse string date

I have a date as string as below

String test Date = "1/31/2020";

I am using the below code

public static String getPeriodMonth(String periodEndDate) {
        LocalDate localDate;
        YearMonth yearMonth = null;
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
            localDate = LocalDate.parse(periodEndDate, formatter);
            yearMonth = YearMonth.from(localDate);
        }catch (Exception e) {
             LOGGER.error("Error: "+ e.getMessage() + ">>" +   e.getCause());
        }
        return yearMonth.toString();

    }

I am getting the below Exception when excuting this code:

Error: Text '1/31/2020' could not be parsed at index 0>>null

Can someone help me what I am doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should pass 01/31/2020or update the format to M/dd/yyyy

DateTimeFormatter documentation

The month is considered as a number and in the documentation :

Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...