0

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

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

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

因为变量在 int 中,所以当 day 例如可以是 01(int 中的 1 位)或 21(int 中的 2 位)时,我遇到了问题,因为我的格式中有 'dd'。有没有一种简单的方法可以使用我的号码来检查日期的有效性?

4

2 回答 2

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();
于 2013-06-12T19:09:04.393 回答
1

您可以像这样填充您的数字字符串:

String paddedDay = String.format("%02d", day);
于 2013-06-12T19:04:02.927 回答