Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 DateTimeFormatter for month in all CAPS not working [duplicate]

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());
}
like image 785
Karthik Prasad Avatar asked Nov 04 '15 11:11

Karthik Prasad


1 Answers

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)
like image 66
Karthik Prasad Avatar answered Sep 28 '22 08:09

Karthik Prasad