在 Java 中检查日期是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4516572/
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
Checking if a date exists or not in Java
提问by sasidhar
Is there any predefined class in Java such that, if I pass it a date it should return if it is a valid date or not? For example if I pass it 31st of February of some year, then it should return false, and if the date exists then it should return me true, for any date of any year.
Java 中是否有任何预定义的类,如果我向它传递一个日期,它是否应该返回一个有效日期?例如,如果我在某年的 2 月 31 日通过它,那么它应该返回 false,如果该日期存在,那么它应该返回 true,对于任何一年的任何日期。
And I also want a method that would tell me what weekday this particular date is. I went through the Calender class but I didn't get how to do this.
而且我还想要一种方法来告诉我这个特定日期是星期几。我参加了日历课程,但我不知道如何做到这一点。
回答by
How to Validate a Date in Java
private static boolean isValidDate(String input) {
String formatString = "MM/dd/yyyy";
try {
SimpleDateFormat format = new SimpleDateFormat(formatString);
format.setLenient(false);
format.parse(input);
} catch (ParseException e) {
return false;
} catch (IllegalArgumentException e) {
return false;
}
return true;
}
public static void main(String[] args){
System.out.println(isValidDate("45/23/234")); // false
System.out.println(isValidDate("12/12/2111")); // true
}
回答by maerics
The key is to call DateFormat#isLenient(false
)so it won't roll values that are out of range during parsing:
关键是调用DateFormat#isLenient( false
)以便在解析过程中不会滚动超出范围的值:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.parse("2010-02-31"); //=> Ok, rolls to "Wed Mar 03 00:00:00 PST 2010".
format.setLenient(false);
format.parse("2010-02-31"); //=> Throws ParseException "Unparseable date".
Of course, you can use any actual date format you require.
当然,您可以使用任何您需要的实际日期格式。
回答by niksvp
You can use this to get weekday from the date
您可以使用它从日期中获取工作日
Calendar currentDate = Calendar.getInstance(); //or your specified date. int weekDay = currentDate.get(Calendar.DAY_OF_WEEK);
Calendar currentDate = Calendar.getInstance(); //or your specified date. int weekDay = currentDate.get(Calendar.DAY_OF_WEEK);