Search code examples
javajava-8java-timedate-parsinglocaldate

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?


Solution

  • 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.