Java:公历日期验证问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7642247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:48:47  来源:igfitidea点击:

Java: Gregorian Calendar date validation issue

javaillegalargumentexception

提问by user873684

I'm trying to validate a date input by a user using the Gregorian Calendar in java (this is a must), however whenever I test a date in December it throws up the error below.

我正在尝试使用 Java 中的公历来验证用户输入的日期(这是必须的),但是每当我测试 12 月的日期时,它都会抛出以下错误。

Exception in thread "main" java.lang.IllegalArgumentException: MONTH   
        at java.util.GregorianCalendar.computeTime(Unknown Source)  
        at java.util.Calendar.updateTime(Unknown Source)  
        at java.util.Calendar.getTimeInMillis(Unknown Source)  
        at java.util.Calendar.getTime(Unknown Source)

code below

下面的代码

public static boolean  ValidDate (int Day, int Month, int Year)  
    GregorianCalendar Date = new GregorianCalendar();  
    Date.setLenient(false);  
    Date.set(Year, Month, Day, 0, 0, 0);  
    try{  
        Date.getTime();  
        return true;  
        }catch (Exception e){  
            System.out.println("Date is invalid please try again");   
            return false;  
        }  
}

I haven't been able to turn up anything relevant on google so any help would be awesome!

我一直无法在谷歌上找到任何相关的东西,所以任何帮助都会很棒!

采纳答案by Basil Bourque

tl;dr

tl;博士

LocalDate.of( year , month , dayOfMonth )  // Catch exception `DateTimeParseException`

java.time

时间

The modern approach uses the java.time classes rather than the troublesome old GregorianCalendarclass.

现代方法使用 java.time 类而不是麻烦的旧GregorianCalendar类。

The java.time.LocalDateclass represents a date-only value without time-of-day and without time zone.

java.time.LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

To validate your inputs, attempt to assemble a LocalDatefrom the numbers. Unlike GregorianCalendar, LocalDatehas sane numbering of months, 1-12 for January-December. If the numbers result in an invalid date, a DateTimeParseExceptionis thrown for you to catch.

要验证您的输入,请尝试LocalDate从数字中组合 a 。与 不同GregorianCalendarLocalDate具有合理的月份编号,1-12 月份为 1-12。如果数字导致日期无效,DateTimeParseException则会抛出a以供您捕获。

try {
    LocalDate ld = LocalDate.of( year , month , dayOfMonth ) ;
    return true ;  // true = Valid data entered for a date.
} catch ( DateTimeParseException e ) {
    return false;  // Exception caught, meaning invalid data-entry.
}


About java.time

关于 java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by Bohemian

With the Calendar class, although days and years arenumbered 1..n(one-based), months are numbered 0-11(zero-based), so December is notmonth number 12, it is month number 11.

对于 Calendar 类,虽然天和年编号的1..n(从一开始),但月份是编号的0-11(从零开始),所以十二月不是月数12,而是月数11

Try calling your method specifying 11(instead of 12) for the month parameter.

尝试调用您的方法1112为月份参数指定(而不是)。

This issue is just oneof the many retarded aspects of the Calendar class.

这个问题仅仅是一个的Calendar类的许多智障方面。

回答by duffymo

Or, better yet, use the constant Calendar.DECEMBER. You don't have to worry about whether it's 11 or 12 under the covers.

或者,更好的是,使用常量Calendar.DECEMBER。您不必担心它是 11 或 12 在封面下。

Do yourself a favor: learn and follow the Java coding standards. I'd write it this way:

帮自己一个忙:学习并遵循 Java 编码标准。我会这样写:

public static boolean  isvalidDate (int day, int month, int year)  
    Calendar calendar = Calendar.getInstance();
    calendar.setLenient(false);  
    calendar.set(year, month, day, 0, 0, 0);  
    try {  
        date.getTime();  
        return true;  
     } catch (Exception e) {  
        return false;  
     }  
 }