我的无效且有效的日期代码未显示

时间:2018-03-14 17:00:21

标签: java date if-statement netbeans java-date

我想编写一个代码来检查日期是否有效但是我的问题在于这里是输出。我无法显示用户是否输入了有效/无效的日期或月份。 Ť

    String date;

   int dd,mm,yyyy;

   boolean leapyear,validdate;




   if(mm >=1 || mm <=12) // to check if user input month which is less than 1 or more than 12
   {
       System.out.println(mm+" is an invalid month");
   }
   if((mm == 4 || mm == 6 || mm == 9 || mm == 11) && (dd <= 30)) // months with 30 days
        {
            validdate = true;
            System.out.println(mm + "/" + dd + "/" + yyyy + " is a valid date.");
        }

        //For months with 31 days
       else if((mm == 1 || mm == 3 || mm== 5 || mm == 7 || mm == 8 || mm == 10 || mm == 12) && (dd <= 31))
        {
            validdate = true;
            System.out.println(mm + "/"+ dd + "/" + yyyy + " is a valid date.");

        }

    else
       {

      System.out.println("Invalid date!");

   }




  }
}

}

2 个答案:

答案 0 :(得分:2)

if(mm >=1 || mm <=12) 

应该是

if (mm < 1 || mm > 12)

否则 mm的每个值将评估为true,使日期&#34;无效&#34;。

答案 1 :(得分:0)

您可以随时使用LocalDatea.of(int year, int month, int dayOfMonth),而不是手动检查每个人(年,月和日)。例如:

LocalDate date;

try {
  date = LocalDate.of(yyyy, mm, dd);
} catch(java.time.DateTimeException e) {
  System.out.println(e.getMessage());
}

如果日期无效,它将抛出异常:

LocalDate localDate = LocalDate.of(2018,2,31);
|  java.time.DateTimeException thrown: Invalid date 'FEBRUARY 31'
|        at LocalDate.create (LocalDate.java:459)
|        at LocalDate.of (LocalDate.java:271)
|        at (#3:1)