我尝试将输入类型 String
转换为 LocalDate
,格式为 "MMM/dd/yyyy"
,但是当我输入输入时,它抛出异常:
Exception in thread "main" java.time.format.DateTimeParseException: Text 'DEC/12/1999' could not be parsed at index 0
这是我的代码:
Scanner sc = new Scanner(System.in);
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MMM/dd/yyyy");
System.out.print("Please enter the first date: ");
LocalDate firstDate = LocalDate.parse(sc.nextLine(), format1);
System.out.print("Please enter the second date: ");
System.out.println(firstDate);
我该如何解决这个问题?
最佳答案
在解析字符串
(如“DEC/12/1999”
)时,您必须注意几件事:
- 月份缩写没有全局标准,它们在语言(例如英语、法语、日语...)和风格(例如是否尾随点)上有所不同
- 解析小写月份缩写和大写月份缩写时存在差异
这就是为什么你必须确保你的 DateTimeFormatter
真正知道要做什么,我认为如果简单地通过 .ofPattern(String, Locale) 构建是不行的
.
为其提供有关要解析的String
的信息:
- 通过应用
parseCaseInsensitive()
使其解析不区分大小写 - 通过定义
Locale
使其考虑语言和风格
您可以使用 DateTimeFormatterBuilder
来执行此操作,下面是一个示例:
public static void main(String[] args) throws IOException {
// example input
String date = "DEC/12/1999";
// Build a formatter, that...
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
// parses independently from case,
.parseCaseInsensitive()
// parses Strings of the given pattern
.appendPattern("MMM/dd/uuuu")
// and parses English month abbreviations.
.toFormatter(Locale.ENGLISH);
// Then parse the String with the specific formatter
LocalDate localDate = LocalDate.parse(date, dtf);
// and print the result in a different format.
System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
输出:
1999-12-12
关于java - 无法在java中将字符串转换为MM/dd/yyyy格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70589689/