DateTimeFormatter Accepting Multiple Dates and Converting to One (java.time library)

前端 未结 4 1207
情话喂你
情话喂你 2020-12-09 06:26

I am trying to write a DateTimeFormatter that will allow me to take in multiple different String formats, and then convert the String

4条回答
  •  生来不讨喜
    2020-12-09 06:52

    What you're asking is not possible.

    DateTimeFormatter is a final class, so you cannot subclass it to implement your own behavior.

    The constructor is package-private, so you can't call it yourself. The only way to create a DateTimeFormatter is by using a DateTimeFormatterBuilder. Note that the static helper methods for creating a DateTimeFormatter are internally using DateTimeFormatterBuilder, e.g.

    public static DateTimeFormatter ofPattern(String pattern) {
        return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter();
    }
    

    DateTimeFormatterBuilder is also a final class, and cannot be subclassed, and it doesn't provide any methods for supplying multiple alternate formats to use, like you want.

    In short, DateTimeFormatter is closed and cannot be extended. If your code can only use a DateTimeFormatter, then you are out of luck.

提交回复
热议问题