SimpleDateFormat print "." for MMM format

Viewed 1172

I am trying to convert date string from one format to another using SimpleDateFormat. Conversion works but there is a dot "." after month.

    String dateStr = "04/02/1987";
    DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
    Date d = df1.parse(dateStr);
    DateFormat df2 = new SimpleDateFormat("dd MMM yyyy");
    System.out.println(df2.format(d));

Output is 04 Feb. 1987 instead of 04 Feb 1987.

2 Answers

What is your Locale.getDefault()?

Different output for alphanumeric date parts may be caused by the Locale the formatter is using. In most cases, the system default Locale is used if you don't specify one yourself. I don't know for sure SimpleDateFormat does so, but it seems likely.

I know that a java.time.format.DateTimeFormatter does so, see the following example which uses java.time, the modern and recommended to use datetime API:

public static void main(String[] args) {
    String dateStr = "04/02/1987";
    LocalDate localDate = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
    System.out.println(localDate.format(DateTimeFormatter.ofPattern("dd MMM yyyy",
                                                                    Locale.ENGLISH)));
    System.out.println(localDate.format(DateTimeFormatter.ofPattern("dd MMM yyyy",
                                                                    Locale.FRENCH)));
}

Output:

04 Feb 1987
04 févr. 1987

The output is (of course) different concerning the name of the month, but using Locale.FRENCH shows a dot after the abbreviated month name. It is possible that your system's default Locale is one that indicates an abbreviation by a dot, too, but is identical to the output format of a Locale.ENGLISH for the numeric parts and the abbreviation of the month.

Please provide Locale.ENGLISH in SimpleDateFormat constructor while creating object as shown below:

String dateStr = "04/02/1987";
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
Date d = df1.parse(dateStr);
DateFormat df2 = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
System.out.println(df2.format(d));
Related