繁体   English   中英

在 Java 中检查日期是否存在

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

Java中是否有任何预定义的类,如果我向它传递一个日期,它是否应该返回它是否是有效日期? 例如,如果我在某年的 2 月 31 日通过它,那么它应该返回 false,如果日期存在,那么它应该返回 true,对于任何一年的任何日期。

而且我还想要一种方法来告诉我这个特定日期是星期几。 我参加了日历课程,但我不知道如何做到这一点。

如何在 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
}

关键是调用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".

当然,您可以使用所需的任何实际日期格式。

您可以使用它从日期获取工作日

 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