gpt4 book ai didi

java - 是否有识别模式本身的 Java 智能日期 API?

转载 作者:行者123 更新时间:2023-12-03 21:29:53 25 4
gpt4 key购买 nike

我有以下输入案例,但我不想自己检查格式并每次都更改模式。我目前使用 DateTimeFormat.forPattern("dd.MM.yyyy");,一旦 a)、c)d) 被应用。

a) 1.1.12      => 01.01.0012 x
b) 01.01.2012 => 01.01.2012 ✓
c) 01.01.12 => 01.01.0012 x
d) 1.1.2012 => 01.00.2012 x

我可以保证格式是 D.M.Y,但如果它是长的或短的或混合的则不是。 Joda 中是否已经有一个函数可以帮助选择“基本模式”上给出的模式?

谢谢!

最佳答案

我使用模式搜索路径。有些日期不明确,因此您需要知道如何处理它们,例如是 1.2.3 Feb 3 AD/1903/2003 的第一天或 1 月的第二天,3 AD 或 1 AD/1901/2001 Feb 的第三天。

我使用的一个简单模式(除了缓存 SimpleDateFormat 对象;)

public static Date parseDate(String dateStr) throws IllegalArgumentException {
// optionally change the separator
dateStr = dateStr.replaceAll("\\D+", "/");

for (String fmt : "dd/MM/yy,yyyy/MM/dd,dd/MM/yyyy".split(",")) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(fmt);
sdf.setLenient(false);
return sdf.parse(dateStr);
} catch (ParseException ignored) {
}
}
throw new IllegalArgumentException("Unable to parse date '" + dateStr + "'");
}

public static void main(String... args) {
String dates = "1.2.12\n" +
"01.02.2012\n" +
"2012.02.01\n" +
"01-01-12\n" +
"1.1.2012";
for (String dateStr : dates.split("\n")) {
Object result;
try {
result = parseDate(dateStr);
} catch (IllegalArgumentException e) {
result = e;
}
System.out.println(dateStr + " => " + result);
}
}

打印

1.2.12 => Wed Feb 01 00:00:00 GMT 2012
01.02.2012 => Wed Feb 01 00:00:00 GMT 2012
2012.02.01 => Wed Feb 01 00:00:00 GMT 2012
01-01-12 => Sun Jan 01 00:00:00 GMT 2012
1.1.2012 => Sun Jan 01 00:00:00 GMT 2012

关于java - 是否有识别模式本身的 Java 智能日期 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9326084/

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