22

JSR-310 has a handy class DateTimeFormatter which allows you to construct a DateTimeFormatter. I particularly like the pattern(String) method - see javadoc

However, I hit a problem whereby this is case sensitive -- e.g.

DateTimeFormatters.pattern("dd-MMM-yyyy");

matches with "01-Jan-2012", but not with "01-JAN-2012" or "01-jan-2012".

One approach would be to break the string down and parse components, or another would be to use Regex to replace the case-insensitive strings with the case-sensitive string.

But it feels like there ought to be an easier way...

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
amaidment
  • 6,942
  • 5
  • 52
  • 88

3 Answers3

29

And there is... according to the User Guide (offline, see JavaDoc instead), you should use DateTimeFormatterBuilder to build a complex DateTimeFormatter

e.g.

DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.parseCaseInsensitive();
builder.appendPattern("dd-MMM-yyyy");
DateTimeFormatter dateFormat = builder.toFormatter();
borjab
  • 11,149
  • 6
  • 71
  • 98
amaidment
  • 6,942
  • 5
  • 52
  • 88
  • 3
    Slightly neater third line: builder.appendPattern("dd-MMM-yyyy"); – JodaStephen Jun 25 '12 at 14:43
  • 2
    Slightly neater: most of the times, a builder provides methods *returning* the builder, so you can use *method chaining*: `new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern...`. – MC Emperor Oct 20 '21 at 19:13
  • 1
    Further improvement: [Never use `SimpleDateFormat` or `DateTimeFormatter` without a `Locale`](https://stackoverflow.com/a/65544056/10819573). Use `.toFormatter(Locale.ENGLISH)` in this case. – Arvind Kumar Avinash Nov 13 '22 at 15:35
10

This alternative is usefull for initializating static variables:

DateTimeFormatter myFormatter = new DateTimeFormatterBuilder()
                               .parseCaseInsensitive()
                               .appendPattern("dd-MMM-yyyy")
                               .toFormatter(Locale.ENGLISH);
borjab
  • 11,149
  • 6
  • 71
  • 98
4

Just an extra Note, the order matters.

This is case insensitive:

            DateTimeFormatter format = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .parseLenient()
                .appendPattern("HH:mm EEEE")
                .toFormatter(); 

This is not:

            DateTimeFormatter format = new DateTimeFormatterBuilder()
                .appendPattern("HH:mm EEEE")
                .parseCaseInsensitive()
                .parseLenient()
                .toFormatter(); 
Jon
  • 1,013
  • 1
  • 10
  • 17
  • Good point! Further improvement: [Never use `SimpleDateFormat` or `DateTimeFormatter` without a `Locale`](https://stackoverflow.com/a/65544056/10819573). Use `.toFormatter(Locale.ENGLISH)` in this case. – Arvind Kumar Avinash Nov 13 '22 at 15:34