检查Java中是否存在日期 [英] Checking if a date exists or not in Java

查看:658
本文介绍了检查Java中是否存在日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我还希望有一种方法可以告诉我这个特定日期是星期几。我经历了日历类,但没有得到如何做。

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.

推荐答案

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

这篇关于检查Java中是否存在日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆