gpt4 book ai didi

dd-MMM-yyyy 格式的 java.time.format.DateTimeParseException

转载 作者:行者123 更新时间:2023-12-01 18:08:43 25 4
gpt4 key购买 nike

我正在尝试解析 dd-MMM-yyyy 的日期格式。

package com.company;

import javax.swing.text.DateFormatter;
import java.time.format.DateTimeFormatter;

import java.time.*;
import java.util.Locale;

public class Main {

public static void main(String[] args) {
// write your code here
MonthDay m;
Locale.setDefault(Locale.ENGLISH);
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String dateString = "12-jan-1900";

try
{
LocalDate ddd = LocalDate.parse(dateString,dTF);
System.out.println(ddd.toString());
}
catch (Exception e)
{
e.printStackTrace();
}

//System.out.println(d.toString());

}
}

它抛出以下异常

java.time.format.DateTimeParseException: Text '12-jan-1900' could not be parsed at index 3
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400)
at com.company.Main.main(Main.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

它可以很好地解析 dd-MM-yyyy格式但失败并显示 dd-MMM-yyyy格式。我厌倦了设置Locale.US也,但在那种情况下也失败了。

最佳答案

原因是解析默认情况下区分大小写,并且格式化程序无法识别“jan”。它只能识别“Jan”

您可以使用 DateTimeFormatterBuilder 构建不区分大小写的解析器。并调用parseCaseInsensitive() :

Changes the parse style to be case insensitive for the remainder of the formatter.

Parsing can be case sensitive or insensitive - by default it is case sensitive. This method allows the case sensitivity setting of parsing to be changed.

DateTimeFormatter dTF = 
new DateTimeFormatterBuilder().parseCaseInsensitive()
.appendPattern("dd-MMM-yyyy")
.toFormatter();

关于dd-MMM-yyyy 格式的 java.time.format.DateTimeParseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60507454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com