验证java中的日期 [英] Validating a date in java

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

问题描述

我正在使用NetBeans IDE 7.2。
我有两个单独的类 newDateTest.java newDateMethod.java ,我正在使用我的方法类验证来自我在测试类中使用的用户输入的日期。



到目前为止,在我的测试类中,我有以下内容:

  try 
{
提示=请输入日期格式为dd-mm-yyyy;
System.out.println(Prompt);
String inputDate = in.next();
isValid = newDateMethod.validDate(input,input,input);
if(isValid){
System.out.println(VALID DATE);

} else {
System.out.println(INVALID DATE);

}

} catch(ArrayIndexOutOfBoundsException oob){
System.out.println(oob);
}
}

然而,我不知道如何验证日期我的方法类,因为我对Java很新。



任何人都可以找到解决方案?我被教导使用的类别是日期制作者,但不知道这是否适合这里?如果这样不知道如何使用它

解决方案

像这样:

  Date date = null; 
String inputDate =07-01-2013​​;
try {
DateFormat formatter = new SimpleDateFormat(dd-MM-yyyy);
formatter.setLenient(false);
date = formatter.parse(inputDate);
} catch(ParseException e){
e.printStackTrace();
}


I am using NetBeans IDE 7.2. I have two seperate classes newDateTest.java and newDateMethod.java, I am currently using my method class to validate a date from a user input which I have used in my test class.

So far in my Test class I have the following:

try
{
    Prompt ="please enter a date in the format dd-mm-yyyy";
    System.out.println(Prompt);
    String inputDate = in.next();
    isValid = newDateMethod.validDate(input, input, input);
    if (isValid){
        System.out.println("VALID DATE");

    } else {
        System.out.println("INVALID DATE");

    }

}catch (ArrayIndexOutOfBoundsException oob) {
    System.out.println(oob);
}
}

However I have no idea how to validate the date in my method class as i am fairly new to Java.

Can anyone come to a solution? the sort iof thing I've been taught to use is Date Formmater but not sure whether this is appropriate here? if so wouldn't know how to use it

解决方案

Like this:

Date date = null;
String inputDate = "07-01-2013";
try {
    DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
    formatter.setLenient(false);
    date = formatter.parse(inputDate);
} catch (ParseException e) { 
    e.printStackTrace();
}

这篇关于验证java中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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