简体   繁体   English

在 Java 中检查日期是否存在

[英]Checking if a date exists or not in Java

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? Java中是否有任何预定义的类,如果我向它传递一个日期,它是否应该返回它是否是有效日期? 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.例如,如果我在某年的 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.我参加了日历课程,但我不知道如何做到这一点。

How to Validate a Date in Java如何在 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 | 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
}

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.当然,您可以使用所需的任何实际日期格式。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM