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

橙三吉。 提交于 2020-06-23 20:32:45

问题


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());
}

回答1:


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)


来源:https://stackoverflow.com/questions/62073296/why-pattern-of-datetimeformat-is-needed-to-avoid-this-causing-a-datetimeparseexc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!