文字列をチェックし、無効な日付を扱います

アンジェリーナ:

私は無効な日付、すなわち遭遇したとき2018-02-31, 2018-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
     */
    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:

parseUnresolvedDatetimeFormatter解析された値の意味を理解しようとせずに解析します。したがって、無効な日付を受け入れ、あなたが作るしようとする前に、解析された値を検査することができ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);
    }
}

のは、あなたの方法のこのバージョンを試してみましょう:

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

出力は次のとおりです。

2018-02-28
2018-02-27

2月31日だから無効だった2018年、その月の最終日だった2月28日、に調整されています。2月27日には有効であるとされているように返されます。

編集:関連する目的の1のためには、はるかに簡単に考えられている場合がありますDateTimeFormatter.ISO_LOCAL_DATE.withResolverStyle(ResolverStyle.LENIENT).parse(nextFieldTypeDate, LocalDate::from)これは、しかし、変わり2018-02-312018-03-03私はあなたが欲しいものではありません理解しています、。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=203323&siteId=1