本文介绍了解析一个没有点的短月份的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,表示法语区域设置中的日期:09-oct-08:

I have a String that represents a date in French locale : 09-oct-08 :

我需要解析那个String让我想出了这个SimpleDateFormat:

I need to parse that String so I came up with this SimpleDateFormat :

String format2 = "dd-MMM-yy";

但是我的月份部分有问题,似乎预计有一个结束点:

But I have a problem with the month part, that seems to be expected with a ending dot :

df2.format(new Date());

给了我:

 28-oct.-09

现在最好的办法是什么让SimpleDateFormat理解(09-oct-08)?

What is now the best way for me to make SimpleDateFormat understand ("09-oct-08") ?

完整代码:

String format2 = "dd-MMM-yy"; 
DateFormat df2 = new SimpleDateFormat(format2,Locale.FRENCH); 
date = df2.parse("09-oct-08"); 

这给了我:java.text.ParseException:Unparseable date:09-oct-08

This gives me : java.text.ParseException: Unparseable date: "09-oct-08"

如果我然后尝试记录:

df2.format(new Date()); 

我得到:28-oct.-09

I get : 28-oct.-09

推荐答案

这似乎有效:

    DateFormatSymbols dfsFr = new DateFormatSymbols(Locale.FRENCH);
    String[] oldMonths = dfsFr.getShortMonths();
    String[] newMonths = new String[oldMonths.length];
    for (int i = 0, len = oldMonths.length; i < len; ++ i) {
        String oldMonth = oldMonths[i];

        if (oldMonth.endsWith(".")) {
            newMonths[i] = oldMonth.substring(0, oldMonths[i].length() - 1);
        } else {
            newMonths[i] = oldMonth;
        }
    }
    dfsFr.setShortMonths(newMonths);
    DateFormat dfFr = new SimpleDateFormat(
        "dd-MMM-yy", dfsFr);

    // English date parser for creating some test data.
    DateFormat dfEn = new SimpleDateFormat(
        "dd-MMM-yy", Locale.ENGLISH);
    System.out.println(dfFr.format(dfEn.parse("10-Oct-09")));
    System.out.println(dfFr.format(dfEn.parse("10-May-09")));
    System.out.println(dfFr.format(dfEn.parse("10-Feb-09")));

编辑:看起来St. Shadow打败了我。

Looks like St. Shadow beat me to it.

这篇关于解析一个没有点的短月份的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 17:48