java.lang.IllegalArgumentException:SimpleDateFormat的非法模式字符’Y’

以下代码:

Calendar now = Calendar.getInstance(); month = now.get(Calendar.MONTH) + 1; year = now.get(Calendar.YEAR); System.out.println("Month " + month + " year " + year); SimpleDateFormat dt1 = new SimpleDateFormat("MMMM YYYY"); e.setMonthnYear(dt1.format(now.getTime())); 

在服务器上部署后显示以下exception:

 java.lang.IllegalArgumentException: Illegal pattern character 'Y' java.text.SimpleDateFormat.compile(SimpleDateFormat.java:768) java.text.SimpleDateFormat.initialize(SimpleDateFormat.java:575) java.text.SimpleDateFormat.(SimpleDateFormat.java:500) java.text.SimpleDateFormat.(SimpleDateFormat.java:475) iland.employee.EmployeeAction.fetchAllAtted(EmployeeAction.java:169) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) 

在我的本地主机上,我使用的是JDK v1.8 ,上面的代码工作正常,但在服务器上却无法正常工作。

我该如何解决这个问题?

尝试

 SimpleDateFormat dt1 = new SimpleDateFormat("MMMM yyyy"); 

在本地,您可能正在使用Java 8,因此请检查服务器上的Java版本。 如果它小于Java 7,则资本Y将不起作用。

请参阅Java 6 Oracle Docs for SimpleDateFormat

你必须写一年的小Y而不是大写。

喜欢两位数的年份:

  SimpleDateFormat dt1 = new SimpleDateFormat("yy"); 

对于4位数的年份:

  SimpleDateFormat dt1 = new SimpleDateFormat("yyyy"); 

如果您使用的是Java 7或更高版本:您可以使用代表Week Year的大写字母Y

请参阅Java 7 Oracle Docs SimpleDateFormat

按照javadocs

 If week year 'Y' is specified and the calendar doesn't support any week years, the calendar year ('y') is used instead. The support of week years can be tested with a call to getCalendar().isWeekDateSupported(). 

因此唯一的问题是猜测你的java版本是否为1.7 <1.7因为JRE1.7为周年添加了'Y'模式而在JRE1.6中没有添加模式。

或者只是停留在更安全的一方使用y而不是Y

还有一件事总是尝试使用locale更安全的一面

 SimpleDateFormat dt1 = new SimpleDateFormat("MMMM yyyy",java.util.Locale.ENGLISH); 

Android的

文档与实现不同。 受支持的字符在SimpleDateFormat中的字符串常量中定义,最高为API级别23. 源代码 :

 static final String PATTERN_CHARS = "GyMdkHmsSEDFwWahKzZLc"; 

由于未包含“Y”(周年),因此模式validation会抛出exception:

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

快速修复,当不需要周年行为时,使用’y’,例如: yyyy-MM-dd

API级别24支持’Y’作为模式字符。

更新

文档现在列出了模式字符支持的API级别。

我从java文档中获取了这个表。

 Letter Date or Time Component Presentation Examples G Era designator Text AD y Year Year 1996; 96 M Month in year Month July; Jul; 07 w Week in year Number 27 W Week in month Number 2 D Day in year Number 189 d Day in month Number 10 F Day of week in month Number 2 E Day in week Text Tuesday; Tue 

在您的情况下,只需将“Y”替换为“y”,您可以在此处查看文档

来自java.text.SimpleDateFormat :

 Letter Date or Time Component Presentation Examples y Year Year 1996; 96 Y Week year Year 2009; 09 

你在SimpleDateFormat()调用中要求Week year而不是year