Java LocalDate Calculate getDate(Console console, Function validator)

Here you can find the source of getDate(Console console, Function validator)

Description

get Date

License

Open Source License

Declaration

static LocalDate getDate(Console console, Function<LocalDate, Boolean> validator) 

Method Source Code


//package com.java2s;
/*/*w  w  w.jav a 2s  .c om*/
 * Copyright (C) 2016 Yadieet SA <yadieet@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.Console;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.function.Function;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern datePattern = Pattern
            .compile("^\\d{1,4}/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])$");
    private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("y/M/d");

    static LocalDate getDate(Console console, Function<LocalDate, Boolean> validator) {
        if (validator == null)
            validator = value -> true;

        String dateStr;
        LocalDate localDate;

        do {
            dateStr = getString(console, value -> datePattern.matcher(value).matches());
            try {
                localDate = LocalDate.parse(dateStr, dateFormatter);
                if (validator.apply(localDate))
                    break;
            } catch (DateTimeParseException ignored) {
            }
        } while (true);

        return localDate;
    }

    static String getString(Console console, Function<String, Boolean> validator) {
        if (validator == null)
            validator = value -> true;

        String value;

        do {
            value = readLine(console);
        } while (!validator.apply(value));

        return value;
    }

    private static String readLine(Console console) {
        console.printf("> ");
        return console.readLine().trim();
    }
}

Related

  1. fastDateWrite(LocalDate localDate)
  2. fastDateWriteWeeks(LocalDate localDate)
  3. getAge(LocalDate birthday)
  4. getAge(LocalDate birthDay)
  5. getDate(ChronoLocalDate date)
  6. getDate(final LocalDate localDate)
  7. getDate(LocalDate d, String tzId)
  8. getDateCriteria(LocalDate startDate, LocalDate endDate)
  9. getDateStart(LocalDate localDate)