Comprobación de cadena y gastos de envío fecha no válida

Angelina:

Cuando me encuentro con fechas no válidos, es decir 2018-02-31, 2018-11-31, quiero que mi código para convertirlo en último día de ese mes.

No estoy seguro de cómo comprobar si el valor dentro de la cadena pasada.

Aquí está mi código hasta ahora:

/**
     * 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;
    }
VV Ole:

El parseUnresolvedmétodo de un DatetimeFormatteranálisis sintácticos sin tratar de dar sentido a los valores analizados. Por lo tanto, acepta una fecha no válida y le permite inspeccionar los valores analizados antes de intentar hacer una LocalDatede ellas.

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);
    }
}

Vamos a probar esta versión del método de salida:

    System.out.println(resolveInvalidDate("2018-02-31"));
    System.out.println(resolveInvalidDate("2018-02-27"));

La salida es:

2018-02-28
2018-02-27

Así 31 de febrero fue inválida y se ha ajustado en 28 de febrero, que en 2018 fue el último día de ese mes. 27 de febrero es válido y se devuelve tal cual.

Editar: Para un solo propósito relacionado podría haber considerado el más fácil DateTimeFormatter.ISO_LOCAL_DATE.withResolverStyle(ResolverStyle.LENIENT).parse(nextFieldTypeDate, LocalDate::from). Esto, sin embargo, se convierte 2018-02-31en 2018-03-03, que entiendo que no es lo que desea.

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=203326&siteId=1
Recomendado
Clasificación