LocalDate - parsing is case sensitive

Viewed 2823
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?

3 Answers

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.

Amend MAY to May, and 1 to 01 and it will work.

Your day part should have two digits, i.e "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);
 }
}
Related