繁体   English   中英

LocalDate - 解析区分大小写

[英]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);
    }
}

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

线程“main”中的异常 java.time.format.DateTimeParseException:无法在 java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) 处的索引 0 处解析文本 'MAY 1 2013' .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);
}

正如parseCaseSensitive()方法的文档所说:

由于默认值区分大小写,因此该方法只能在先前调用 #parseCaseInsensitive 之后使用。

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

您的一天部分应该有两位数字,即"MAY 01 2013"

然后,如果您真的想传递大写的月份名称,则应该将构建器与parseCaseInsensitive()一起使用。

把它们放在一起:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM