Java 检查字符串并处理无效日期
当我遇到无效日期时,即2018-02-312018-11-31,我希望我的代码将其转换为该月的最后一天 我不知道如何检查传递的字符串中的值 以下是我目前的代码:Java 检查字符串并处理无效日期,java,datetime,Java,Datetime,当我遇到无效日期时,即2018-02-312018-11-31,我希望我的代码将其转换为该月的最后一天 我不知道如何检查传递的字符串中的值 以下是我目前的代码: /** * If date comes back as invalid, i.e. 2018-11-31 * convert it to have last day of given month. * * @param nextFieldTypeDate * @return
/**
* If date comes back as invalid, i.e. 2018-11-31
* convert it to have last day of given month.
*
* @param nextFieldTypeDate
* @return
*/
public static LocalDate resolveInvalidDate(String nextFieldTypeDate) {
LocalDate convertedDate = null;
try {
convertedDate = LocalDate.parse(nextFieldTypeDate);
} catch(DateTimeException dte) {
//convertedDate = convert date to have last day of the month
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM");
String yearMonthString = nextFieldTypeDate.subSequence(0, 7).toString();
YearMonth ym = YearMonth.parse(yearMonthString, fmt);
convertedDate = ym.atEndOfMonth();
} catch(Exception e) {
logger.error(e.getMessage());
throw new ConversionException("Unable to convert nextFieldTypeDate.", e);
}
return convertedDate;
}
DatetimeFormatter
的parseUnresolved
方法在解析时不试图理解解析的值。因此,它接受一个无效的日期,并允许您在尝试对解析的值进行LocalDate
之前检查这些值
public static LocalDate resolveInvalidDate(String nextFieldTypeDate) {
ParsePosition position = new ParsePosition(0);
TemporalAccessor parsed = DateTimeFormatter.ISO_LOCAL_DATE
.parseUnresolved(nextFieldTypeDate, position);
if (position.getIndex() < nextFieldTypeDate.length()) {
throw new IllegalArgumentException("Could not parse entire string");
}
YearMonth ym = YearMonth.from(parsed);
int lastDayOfMonth = ym.lengthOfMonth();
int parsedDayOfMOnth = parsed.get(ChronoField.DAY_OF_MONTH);
if (parsedDayOfMOnth > lastDayOfMonth) { // invalid, must be adjusted to lasst day of month
return ym.atEndOfMonth();
} else {
return ym.atDay(parsedDayOfMOnth);
}
}
输出为:
因此,2月31日无效,已调整为2月28日,2018年是该月的最后一天。2月27日有效,并按原样返回
编辑:出于相关目的,人们可能会考虑更简单的
DateTimeFormatter.ISO\u LOCAL\u DATE.withResolverStyle(ResolverStyle.LENIENT).parse(nextFieldTypeDate,LocalDate::from)
。然而,这将2018-02-31
变成2018-03-03
,我知道这不是您想要的。不是最干净的解决方案,但这应该可以:
public static LocalDate resolveInvalidDate(String nextFieldTypeDate) {
LocalDate convertedDate = null;
try {
convertedDate = LocalDate.parse(nextFieldTypeDate);
} catch(DateTimeException dte) {
//convertedDate = convert date to have last day of the month
Integer[] constituents = Arrays.stream(nextFieldTypeDate.split("-"))
.map(constituentString -> Integer.valueOf(constituentString))
.toArray(Integer::new);
LocalDate defaultDate = LocalDate.of(constituents[0], constituents[1], 1);
LocalDate convertedDate = LocalDate.of(defaultDate.getYear(), defaultDate.getMonth(), defaultDate.lengthOfMonth());
} catch(Exception e) {
logger.error(e.getMessage());
throw new ConversionException("Unable to convert nextFieldTypeDate.", e);
}
return convertedDate;
}
当我通过2018-14-25时,它在YearMonth ym=YearMonth.from(解析)上爆炸;是的。你想把14号调成12号吗?你可能想在你的问题中加上这个。不。我将它放在try-catch中,并在无效月份抛出异常
2018-02-28
2018-02-27
public static LocalDate resolveInvalidDate(String nextFieldTypeDate) {
LocalDate convertedDate = null;
try {
convertedDate = LocalDate.parse(nextFieldTypeDate);
} catch(DateTimeException dte) {
//convertedDate = convert date to have last day of the month
Integer[] constituents = Arrays.stream(nextFieldTypeDate.split("-"))
.map(constituentString -> Integer.valueOf(constituentString))
.toArray(Integer::new);
LocalDate defaultDate = LocalDate.of(constituents[0], constituents[1], 1);
LocalDate convertedDate = LocalDate.of(defaultDate.getYear(), defaultDate.getMonth(), defaultDate.lengthOfMonth());
} catch(Exception e) {
logger.error(e.getMessage());
throw new ConversionException("Unable to convert nextFieldTypeDate.", e);
}
return convertedDate;
}