gpt4 book ai didi

java - 将日期从 DD-MMM-YYYY 重新格式化为 YYYYDDMM 或 YYYYMMDD

转载 作者:行者123 更新时间:2023-11-30 10:24:11 26 4
gpt4 key购买 nike

我正在尝试使用 Java 8 重新格式化今天的日期,但出现以下错误:

java.time.format.DateTimeParseException: Text '09-OCT-2017' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2017, MonthOfYear=10, DayOfYear=9},ISO of type java.time.format.Parsed  

代码:

public static String formatDate(String inputDate, String inputDateFormat, String returnDateFormat){
try {
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern(inputDateFormat).toFormatter(Locale.ENGLISH);
LocalDate localDate = LocalDate.parse(inputDate, inputFormatter);

DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(returnDateFormat);
String formattedString = localDate.format(outputFormatter);
return formattedString;
} catch (DateTimeParseException dtpe) {
log.error("A DateTimeParseException exception occured parsing the inputDate : " + inputDate + " and converting it to a " + returnDateFormat + " format. Exception is : " + dtpe);
}
return null;
}

我以前尝试过使用 SimpleDateFormat,但问题是我的 inputDateFormat 格式总是大写 DD-MMM-YYYY,这给了我的结果不正确,所以我尝试使用 parseCaseInsensitive() 来忽略区分大小写。

最佳答案

In the comments你告诉输入格式是 DD-MMM-YYYYAccording to javadoc ,大写的 DDday of year 字段,YYYYweek based year 字段(可能是different from the year field ).

您需要将它们更改为小写的 dd(月份的日期)和 yyyy(时代的年份 ). parseCaseInsensitive() 只处理 text 字段 - 在这种情况下,月份名称(数字不受区分大小写的影响 - 只是因为月份是大写的,这并不意味着数字模式也应该是)。

其余的代码是正确的。示例(将格式更改为 yyyyMMdd):

String inputDate = "09-OCT-2017";
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
// use "dd" for day of month and "yyyy" for year
.appendPattern("dd-MMM-yyyy")
.toFormatter(Locale.ENGLISH);
LocalDate localDate = LocalDate.parse(inputDate, inputFormatter);

// use "dd" for day of month and "yyyy" for year
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
String formattedString = localDate.format(outputFormatter);
System.out.println(formattedString); // 20171009

上面代码的输出是:

20171009


关于 your other comment关于无法控制输入模式,一种替代方法是手动将字母替换为小写版本:

String pattern = "DD-MMM-YYYY";
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
// replace DD and YYYY with the lowercase versions
.appendPattern(pattern.replace("DD", "dd").replaceAll("YYYY", "yyyy"))
.toFormatter(Locale.ENGLISH);
// do the same for output format if needed

我不认为它需要一个complex-replace-everything-in-one-step 正则表达式。只需多次调用 replace 方法就可以解决问题(除非您有真的复杂的模式,需要多次不同且复杂的 replace 调用,但仅使用您提供的案例就足够了)。

关于java - 将日期从 DD-MMM-YYYY 重新格式化为 YYYYDDMM 或 YYYYMMDD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46645073/

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