15

I'm trying to parse date time string to LocalDateTime. However if I send month with all caps its thorwning an error, is there any workaround. Here is the below code

@Test
public void testDateFormat(){
    DateTimeFormatter formatter= DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss");
    LocalDateTime dateTime = LocalDateTime.parse("04-NOV-2015 16:00:00", formatter); //if I send month Nov it works
    System.out.println(dateTime.getYear());
}

The Same works for simpleDateFormat

@Test
public void testSimpleDateTime() throws ParseException{
    SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
    Date dateTime = format.parse("04-NOV-2015 16:00:00");
    System.out.println(dateTime.getTime());
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Karthik Prasad
  • 9,662
  • 10
  • 64
  • 112
  • maybe ResolverStyle.SMART (the default) doesn't handle this: https://docs.oracle.com/javase/8/docs/api/java/time/format/ResolverStyle.html – blank Nov 04 '15 at 11:46

1 Answers1

43

Answering this question because most of us might not know JSR 310. Hence would search for java 8 LocalDateTime ignore case.

@Test
public void testDateFormat(){
    DateTimeFormatter formatter= new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("dd-MMM-yyyy HH:mm:ss").toFormatter();
    LocalDateTime dateTime = LocalDateTime.parse("04-NOV-2015 16:00:00", formatter);
    System.out.println(dateTime.getYear());
}

**UPDATE*

To locale

DateTimeFormatter parser = new DateTimeFormatterBuilder().parseCaseInsensitive() .appendPattern("dd-MMM-yyyy HH:mm:ss.SS").toFormatter(Locale.ENGLISH)
Karthik Prasad
  • 9,662
  • 10
  • 64
  • 112