How to force 4 digit year format in <f:convertDateTime>

converters, date, jsf-2

Solution

This isn't a bug. That's just how `SimpleDateFormat` works. Here's a cite of relevance from the linked javadoc:

- Year: If the formatter's `Calendar` is the Gregorian calendar, the following rules are applied.

- ...

- For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.

- ...

The JSF `<f:convertDateTime>` is just using it under the covers. Your best bet is to extend the `DateTimeConverter` and validate the length of the submitted value before passing through to the real `DateTimeConverter`. You can't go around creating a custom converter, but it's after all fairly simple.

@FacesConverter("myDateTimeConverter")
public class MyDateTimeConverter extends DateTimeConverter {

    public MyDateTimeConverter() {
        setPattern("MM/dd/yyyy");
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value != null && value.length() != getPattern().length()) {
            throw new ConverterException("Invalid format");
        }
        return super.getAsObject(context, component, value);
    }

}

Use it as follows:

<h:inputText ... converterMessage="Please enter date in MM/dd/yyyy format">
    <f:converter converterId="myDateTimeConverter" />
</h:inputText>

Please note that I fixed the `mm` (minutes) in the pattern to be `MM` (months).

Problem

I am using JSF 2.0 and RichFaces 4. For the date input, I am trying to force the pattern `mm/dd/yyyy`. ``` <h:inputText value="#{bean.startDate}"> <f:convertDateTime pattern="mm/dd/yyyy"/> </h:inputText> ``` When user actually enters a date with a 2-digit year like so `mm/dd/yy`, then the converter automatically converts the year to 4 digits. This is undesired. How can I stop it from doing that without creating a custom converter? Is this a bug in the JSF converter?

Original source