【问题标题】:Throw error for invalid LocalDate dates为无效的 LocalDate 日期引发错误
【发布时间】:2018-04-03 21:45:48
【问题描述】:

我最近开始在 Java 中使用 util.Date,只是得知不能加/减天数,所以我现在开始使用 LocalDate。

我有一个网络应用程序,允许用户以“dd/MM/yyyy”格式输入日期,并且需要将其转换为“yyyy-MM-dd”。如果输入的日期不存在,应用程序也需要抛出错误。

下面是我正在使用的测试应用程序。它有效,但错误地允许像“31/02/2018”这样的日期。我尝试添加“.withResolverStyle(ResolverStyle.STRICT)”,但出现不同的错误。

package javaapplication1;

import java.text.ParseException;
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.time.format.ResolverStyle;

public class JavaApplication1 {

    public static void main(String[] args) {

        LocalDate today = LocalDate.now();

        LocalDate date;

        try {
            String strDate = "31/2/09"; // Input from user
            System.out.println("Form: " + strDate);

            date = setDate(strDate, "d/M/yy");

            System.out.println("Data: " + convertDateToString(date, "yyyy-MM-dd")); // Convert format for insertting into database

            // If date is older than 1 year, output message
            if (date.isBefore(today.minusYears(1))) {
                System.out.println("Date is over a year old");
            }

            // If date is older than 30 days, output message
            if (date.isBefore(today.minusDays(30))) {
                System.out.println("Date is over 30 days old");
            }
        }
        catch (ParseException e) {
            System.out.println("Invalid date!");
            e.printStackTrace();
        }
    }

    private static LocalDate setDate(String strDate, String dateFormat) throws ParseException {

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat).withResolverStyle(ResolverStyle.STRICT);

        //sdf.setLenient(false);

        LocalDate date = LocalDate.parse(strDate, dtf);

        return date;
    }

    private static String convertDateToString(LocalDate date, String dateFormat) {

        //DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);

        String strDate = date.toString();

        return strDate;
    }
}

【问题讨论】:

  • 所以用户应该输入像31/2/2018这样的日期并且你想在输入'31/02/2018时抛出错误?
  • 对不起,没有。应该抛出一个错误,因为 2 月没有第 31 天。 28/2/18 和 28/02/2018 都应该被接受而没有错误
  • 谢谢。我的答案埋在那里,但我发现我需要抛出 DateTimeParseExeption ,并出于某种原因在我的日期格式中使用 uu 而不是 yy
  • @smally 请将您的解决方案作为答案发布并接受以关闭此问题。

标签: java


【解决方案1】:

改用 DateTimeParseExeption 解决了问题。

ResolverStyle.STRICT 需要使用 'uuuu' 而不是 'yyyy' 来表示年份。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    相关资源
    最近更新 更多