从数字中解析并检查日期的有效性

时间:2013-06-12 19:02:34

标签: java

我想检查日期的存在,我有int变量(代表格式) - 日(dd),月(MM)和年(YY)。这是我的代码:

    SimpleDateFormat df = new SimpleDateFormat("YYMMdd");
    df.setLenient(false);

    try {
        Date d = df.parse(""+day+month+year);
    } ...

因为变量在int中我有问题,例如当天可以是01(int中的1位)或21(int中的2位)并且我得到错误,因为我的'dd'在我的格式中。有一种简单的方法可以用我的数字来检查日期的有效性吗?

2 个答案:

答案 0 :(得分:3)

如果你有数字格式的日,月和年,直接创建日期会更容易:

Calendar cal = Calendar.getInstance();
cal.clear(); //to set the time to 00:00:00.0000 if that is an issue
cal.set(year, month, day);
Date dt = cal.getTime();

答案 1 :(得分:1)

您可以填写数字字符串,如下所示:

String paddedDay = String.format("%02d", day);