java - 无法在java中将字符串转换为MM/dd/yyyy格式

标签 java java-time datetimeformatter

我尝试将输入类型 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/

相关文章:

java - Apache TomEE Webprofile 8 - 无法将 Json Rest 提供程序从 Johnzon 更改为 Jackson

java - 如何释放 Activity 完成的线程?

java - 从 OffsetDateTime 中删除分钟、秒和纳秒

java - 为什么Java的java.time.format.DateTimeFormatter#format(LocalDateTime)要加一年?

datetime - 数据库DateTime毫秒和纳秒如果为0则默认被截断,而在Java 11中使用ZonedDateTime时使用它

java - java中的继承继承变量?

java - 从 PHP 发送到另一个 (Java) Web 服务并检索(图像)结果

Java 8 LocalDateTime 今天在特定时间

java - 使用 DateTimeFormatter 显示短时区名称

java - DateTimeFormatter 用区域偏移量和时区解析字符串