简体   繁体   中英

LocalDate - parsing is case sensitive

public class Solution {

    public static void main(String[] args) {
        System.out.println(isDateOdd("MAY 1 2013"));
    }

    public static boolean isDateOdd(String date) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy");
        formatter = formatter.withLocale(Locale.ENGLISH); 
        LocalDate outputDate = LocalDate.parse(date, formatter);
        return ((outputDate.getDayOfYear()%2!=0)?true:false);
    }
}

I want to know, if number of days, that passed from beginning of the year to some date is odd. I try to use LocalDate to parse date from my string ( MAY 1 2013 ), but I get error:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'MAY 1 2013' could not be parsed at index 0 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) at java.time.LocalDate.parse(LocalDate.java:400) at com.javarush.task.task08.task0827.Solution.isDateOdd(Solution.java:23) at com.javarush.task.task08.task0827.Solution.main(Solution.java:16)

Where's a problem?

If you want to use the month's input with all the capital letters, ex. MAY , you have to use the case-insensitive DateTimeFormatter:

public static boolean isDateOdd(String date) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("MMM d yyyy")
            .toFormatter(Locale.ENGLISH);
    LocalDate outputDate = LocalDate.parse(date, formatter);
    return (outputDate.getDayOfYear() % 2 != 0);
}

As the documentation of the parseCaseSensitive() method says:

Since the default is case sensitive, this method should only be used after a previous call to #parseCaseInsensitive.

MAY修改为May ,将1修改为01 ,它将起作用。

Your day part should have two digits, ie "MAY 01 2013" .

Then if you really want to pass upper-case month names, you should use a builder along with parseCaseInsensitive() .

Putting it all together :

public static boolean isDateOdd(String date) {

    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
    builder.parseCaseInsensitive();
    builder.appendPattern("MMM dd yyyy");
    DateTimeFormatter formatter = builder.toFormatter(Locale.ENGLISH); 

    LocalDate outputDate = LocalDate.parse(date, formatter);
    return ((outputDate.getDayOfYear()%2!=0)?true:false);
 }
}

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