我正在使用SImpleDateFormat面对法语区域设置的ParseException

时间:2016-03-25 05:13:13

标签: java date localization

我在法语区域设置中使用SimpleDateFormat获取ParseException。 其他语言环境也存在问题,但我只是调试了法语。我从UI日历中选择日期(比如01-Avr-2016,格式为“dd-MMM-yyyy”),当我将其传递给我的代码时:

String dateval = "01-Avr-2016";
Locale lformat = Locale.getDefault();
DateFormat specifiedDateFormat = new SimpleDateFormat( "dd-MMM-yyyy", lformat );
specifiedDateFormat.parse( dateval );

以上代码抛出错误。我发现SimpleDateFormat中的shortmonth伴随着句点(“。”)(对于上面的例子,它将是“avr。”)并且我可以编写一些逻辑来处理句点,但我不想为法语编写任何特定的逻辑语言环境。 相反,我想知道为什么从日历(来自DateComponent)选择的月份为“Avr”而不是“avr。”?我该如何处理该用例?

2 个答案:

答案 0 :(得分:2)

首先,您的错误来自于parse()方法抛出ParseException的事实。你需要处理它。

其次,在法国语言环境中,预计缩短的月份将在缩写后的一段时间内给出。如果您可以处理添加期间,则应该没有问题。因为“01-avr.-2016”和“01-Avr.-2016”都是有效的可解析日期。

关于在Parsing French Dates in Java

解析法语日期有一个很好的相关问题
String dateval = "01-avr.-2016";
Locale lformat = Locale.FRENCH;
DateFormat specifiedDateFormat = new SimpleDateFormat( "dd-MMM-yyyy", lformat );
try{
specifiedDateFormat.parse( dateval );
}
catch(ParseException pe){
    pe.printStackTrace();
    //or whatever logic you want to do on an invalid entry
}

如果您想直接处理“avr”或“Avr”,请按以下方式使用Joda Time

LocalDate frenchDate = DateTimeFormat.forPattern("dd-MMM-yyyy").withLocale( Locale.FRENCH ).parseLocalDate("01-Avr-2016");

答案 1 :(得分:1)

Java 8中的Date Time Api,您可以这样使用

// french date formatting (1. avril 2014)
String frenchDate = dateTime.format(DateTimeFormatter.ofPattern("d. MMMM yyyy", new Locale("fr")));

更多信息:

  1. http://www.mscharhag.com/java/java-8-date-time-api
  2. 下表显示了如何使用French locales:

    为每种样式设置日期格式

    Sample Date Formats of French is given below

    Style   French Locale
    
    DEFAULT 30 juin 2009
    
    SHORT   30/06/09
    
    MEDIUM  30 juin 2009
    
    LONG    30 juin 2009
    
    FULL    mardi 30 juin 2009
    

    <强>更新

    使用DateFormat.getDateInstance(int style, Locale locale)而非使用SimpleDateFormat创建自己的模式。