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
Java: Gregorian Calendar date validation issue
提问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 GregorianCalendar
class.
现代方法使用 java.time 类而不是麻烦的旧GregorianCalendar
类。
The java.time.LocalDate
class represents a date-only value without time-of-day and without time zone.
该java.time.LocalDate
级表示没有时间一天和不同时区的日期,唯一的价值。
To validate your inputs, attempt to assemble a LocalDate
from the numbers. Unlike GregorianCalendar
, LocalDate
has sane numbering of months, 1-12 for January-December. If the numbers result in an invalid date, a DateTimeParseException
is thrown for you to catch.
要验证您的输入,请尝试LocalDate
从数字中组合 a 。与 不同GregorianCalendar
,LocalDate
具有合理的月份编号,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 类?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABPproject adapts ThreeTen-Backport(mentioned above) for Android specifically.
- See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 所述ThreeTenABP项目适应ThreeTen-反向移植(上述)为Android特异性。
- 请参阅如何使用ThreeTenABP ...。
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 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答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.
尝试调用您的方法11
,12
为月份参数指定(而不是)。
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;
}
}