java - LocalDate - 解析区分大小写

标签 java java-8 java-time date-parsing localdate

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);
    }
}

我想知道从年初到某个日期的天数是否为奇数。我尝试使用 LocalDate 从我的字符串 (MAY 1 2013) 中解析日期,但出现错误:

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)

哪里出了问题?

最佳答案

如果你想使用所有大写字母的月份输入,例如 MAY,你必须使用不区分大小写的 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);
}

作为documentation parseCaseSensitive() 方法说:

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

关于java - LocalDate - 解析区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46486822/

相关文章:

j2mepolish 中的 java.io.File 不工作

java - 如何使用 select * 从数据库中选择唯一的列值?

scala - 我可以在 Scala Play 2.3.8 项目中使用新的 java 8 time API 吗?

Java 8 日期时间格式日期+偏移量

java - 按日期分组项目

java - GAE+Objectify 类层次结构和引用(...)

java - jOOQ - 监听器

java - JAVA中如何组合两种方法?

java - 使用java流获取逗号分隔的字符串

java - 某些标点字符与启用的 Pattern.UNICODE_CHARACTER_CLASS 标志不匹配