如何在java中使用date API验证年份

时间:2013-11-28 14:36:20

标签: java

我写了一些验证日期的代码,但为什么它不验证年份? 如果没有错误,请参阅 1234 无效年份。

try {
        SimpleDateFormat df = new java.text.SimpleDateFormat("MM/dd/yyyy");
        df.setLenient(false);
        Date date=df.parse("10/4/1234");
        System.out.println("date------->"+date);
    } catch (java.text.ParseException e) {
       e.printStackTrace();
    }

sql server中的错误过程:

  

SELECT @CONVERT_DATETIME = convert(datetime,@ DB_DATE,103);

     

SET @STORE_DB = CAST((CAST(DATEDIFF(s,'1970-01-01',ltrim(rtrim(@CONVERT_DATETIME)))bigint))* 1000 - @ GMT5)as varchar(MAX)) ;

2 个答案:

答案 0 :(得分:2)

1234当然是有效的一年。

如果您想要更多限制,可以使用GregorianCalendar来验证年份。 例如:

Calendar cal = GregorianCalendar.getInstance();
cal.setTime(myDate);
if (cal.get(Calendar.YEAR) < 1970) {
    throw new ParseException("Date under 1970 are not allowed!", 6);
}

答案 1 :(得分:1)

如上所述1234是有效年份。我假设你想要一种方法来确定1234不是需要使用的正确年份。

您可以从字符串中提取年份并进行简单比较。

try {
        SimpleDateFormat df = new java.text.SimpleDateFormat("MM/dd/yyyy");

        Calendar c = Calendar.getInstance();
        c.setTime(df.parse("10/4/1234"));

        System.out.println("Year = " + c.get(Calendar.YEAR));
        // check the condition whether year is valid
        if( c.get(Calendar.YEAR) < 1970 ) {
            System.out.println("Invalid Year entered");
            // you can throw an exception here if you want
        }
    } catch (java.text.ParseException e) {
       e.printStackTrace();
    }

您可以使用Calendar API提取日,月,分,秒等。

在您的示例中,如果您使用

,则会发生ParseException
the date "10/4/12345"

以下格式

SimpleDateFormat("MM/dd/yyyy");

因为12345与“yyyy”不匹配