在Java8中,当用户输入错误的日期格式时,如何给出错误消息
如果用户使用错误的格式输入,我想给出一条错误消息。正确的格式为“yyyy-MM-dd HH:MM:ss”。我怎么能把它作为一个条件呢 比如说在Java8中,当用户输入错误的日期格式时,如何给出错误消息,java,datetime-format,localdate,Java,Datetime Format,Localdate,如果用户使用错误的格式输入,我想给出一条错误消息。正确的格式为“yyyy-MM-dd HH:MM:ss”。我怎么能把它作为一个条件呢 比如说 如果(yyyy您可以使用正则表达式比较: while input doesn't match the regex pattern print "Please enter date in the correct format: yyyy-MM-dd HH:mm:ss" continue with the rest of the code 正则表达
如果(yyyy您可以使用正则表达式比较:
while input doesn't match the regex pattern
print "Please enter date in the correct format: yyyy-MM-dd HH:mm:ss"
continue with the rest of the code
正则表达式模式可以是:
\d{4}-[01]\d-[0-3]\d[0-2]\d:[0-5]\d:[0-5]\d(?:。\d+)?Z
如果用户只需输入一个日期(如
2019-03-31
),那么您可以使用site创建和测试正则表达式模式。您的程序没有理由也关注一天中的时间。此外,您的格式是ISO 8601,LocalDate
的格式,另一种是java.time解析(以及打印)类作为默认设置。因此您不需要显式格式化程序
我知道您需要范围检查,这当然是明智的。此外,如果用户输入完全不同的格式,解析将抛出一个DateTimeParseException
,您应该捕获该异常并相应地采取行动。例如:
LocalDate minAcceptedDate = LocalDate.of(0, Month.JANUARY, 1);
LocalDate maxAcceptedDate = LocalDate.of(4000, Month.DECEMBER, 31);
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter Date : ");
while (true) {
String time = keyboard.next();
try {
LocalDate dateTime = LocalDate.parse(time);
if (dateTime.isBefore(minAcceptedDate) || dateTime.isAfter(maxAcceptedDate)) {
System.out.println("Please enter a date in the range " + minAcceptedDate + " through " + maxAcceptedDate);
} else { // OK
break;
}
} catch (DateTimeParseException dtpe) {
System.out.println("Please enter a date in format yyyy-mm-dd");
}
}
示例会话:
Please enter Date :
Yesterday
Please enter a date in format yyyy-mm-dd
-001-12-30
Please enter a date in format yyyy-mm-dd
5000-12-12
Please enter a date in the range 0000-01-01 through 4000-12-31
2016-09-22
Please enter Date :
Yesterday
Please enter a date in format yyyy-mm-dd
-001-12-30
Please enter a date in format yyyy-mm-dd
5000-12-12
Please enter a date in the range 0000-01-01 through 4000-12-31
2016-09-22