【问题标题】:LocalDate - parsing is case sensitiveLocalDate - 解析区分大小写
【发布时间】:2018-03-11 05:46:40
【问题描述】:
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) 中解析日期,但出现错误:

线程“主”java.time.format.DateTimeParseException 中的异常:无法在索引 0 处解析文本“2013 年 5 月 1 日” 在 java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) 在 java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) 在 java.time.LocalDate.parse(LocalDate.java:400) 在 com.javarush.task.task08.task0827.Solution.isDateOdd(Solution.java:23) 在 com.javarush.task.task08.task0827.Solution.main(Solution.java:16)

哪里出了问题?

【问题讨论】:

  • MAY 01 2013 怎么样?
  • 刚才试过了,还是不行。
  • 可能也应该是可能@nullpointer

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


【解决方案1】:

MAY修改为May,将1修改为01即可。

【讨论】:

    【解决方案2】:

    你的一天部分应该有两位数,即"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);
     }
    }
    

    【讨论】:

      【解决方案3】:

      如果要使用所有大写字母的月份输入,例如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() 方法的documentation 所说:

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

      【讨论】:

      • 是的!问题出在 parseCaseInsensitive 中。谢谢你。因此,如果没有 .parseCaseIntensitive,它只能与“May 01 1998”一起使用,不是吗?
      • 不区分大小写意味着处理不受字母大小写的影响。因此,本月的所有大小写变化都将起作用:mAyMAYmaymAY 等...
      • @Aldres,你是对的,默认区分大小写的解析只会识别 May(大写 M,小 ay)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 2013-05-24
      • 1970-01-01
      • 2017-11-12
      • 2012-03-09
      • 2011-08-30
      • 1970-01-01
      相关资源
      最近更新 更多