java.lang.IllegalArgumentException: Illegal pattern character 'Y' for SimpleDateFormat

后端 未结 6 1555
小蘑菇
小蘑菇 2020-12-18 17:44

The following code:

Calendar now = Calendar.getInstance();
month = now.get(Calendar.MONTH) + 1;
year = now.get(Calendar.YEAR);
System.out.println(\"Month \"          


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-18 18:13

    Android

    The documentation differs from the implementation. The supported characters are defined in a string constant in SimpleDateFormat up to API level 23. From the source code:

    static final String PATTERN_CHARS = "GyMdkHmsSEDFwWahKzZLc";
    

    Since 'Y' (Week Year) is not included, the pattern validation throws the exception:

    java.lang.IllegalArgumentException: Unknown pattern character 'Y'
    

    A quick fix, when week year behaviour isn't required, is to use the 'y', e.g.: yyyy-MM-dd.

    'Y' as a pattern character is supported as of API level 24.

    Update

    The documentation now lists the supported API levels for pattern characters.

提交回复
热议问题