Java 8 DateTimeFormatter在所有CAPS中的月份不起作用 [英] Java 8 DateTimeFormatter for month in all CAPS not working

查看:71
本文介绍了Java 8 DateTimeFormatter在所有CAPS中的月份不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将日期时间字符串解析为LocalDateTime.但是,如果我将所有大写的月份发送给我,则报错,是否有任何解决方法.这是下面的代码

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

simple适用于simpleDateFormat

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

推荐答案

回答这个问题,因为我们大多数人可能不了解JSR310.因此将搜索java 8 LocalDateTime忽略大小写.

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)

这篇关于Java 8 DateTimeFormatter在所有CAPS中的月份不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆