Parsing a date with short month without dot

后端 未结 6 1723
情书的邮戳
情书的邮戳 2020-12-10 02:19

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

I need to parse that String so I came up with this SimpleDa

6条回答
  •  情歌与酒
    2020-12-10 02:28

    You can simply remove the ".":

    df2.format(new Date()).replaceAll("\\.", ""));
    

    Edit, regarding the lemon answer:

    It seems to be a problem with the formatting when using the Locale French. Thus, I suggest that you simply use the . removal as I explained.

    Indeed, the following code:

        String format2 = "dd-MMM-yy";
        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat sdf = new SimpleDateFormat(format2, Locale.FRENCH);
        System.out.println(sdf.format(date));
        sdf = new SimpleDateFormat(format2, Locale.ENGLISH);
        System.out.println(sdf.format(date));
    

    displays the following output:

    28-oct.-09
    28-Oct-09
    

    Edit again

    Ok, I got your problem right now.

    I don't really know how you can solve this problem without processing your String first. The idea is to replace the month in the original String by a comprehensive month:

            String[] givenMonths = { "jan", "fév", "mars", "avr.", "mai", "juin", "juil", "août", "sept", "oct", "nov", "déc" };
            String[] realMonths = { "janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc." };
            String original = "09-oct-08";
            for (int i = 0; i < givenMonths.length; i++) {
                original = original.replaceAll(givenMonths[i], realMonths[i]);
            }
            String format2 = "dd-MMM-yy";
            DateFormat df2 = new SimpleDateFormat(format2, Locale.FRENCH);
            Date date = df2.parse(original);
            System.out.println("--> " + date);
    

    I agree, this is awful, but I don't see any other solution if you use to SimpleDateFormat and Date classes.

    Another solution is to use a real date and time library instead of the original JDK ones, such as Joda Time.

提交回复
热议问题