检查日期是否有效

时间:2020-05-23 01:59:35

标签: java

我正在尝试在Java中创建一个方法来检查日期是否有效 格式为MM / dd / yyyy

public static boolean checkDate(String date)
{
    Calendar cal = Calendar.getInstance();
    int year=0,month=0,day=0;
    int year2;

    year=Integer.parseInt(date.substring(6));
    day=Integer.parseInt(date.substring(3,5));
    month=Integer.parseInt(date.substring(0,2));

    year2=cal.get(Calendar.YEAR);

    if(date.length() != 10)
        return false;
    if(year==year2||year<=year2-100)
        return true;
    else if(month>12||month<1)
        return true;
    else if(day<1)
        return true;
    else if(month==2&&day>28)
        return true;
    else if((month==1||month==3||month==5||month==7||month==8||month==10||month==12)&&day>31)
        return true;
    else if((month!=1||month!=3||month!=5||month!=7||month!=8||month!=10||month!=12)&&day>31)
        return true;
    else
        return false;
}

由于某种原因,它不起作用,我也不知道为什么。如果有人看到我是否犯了一个简单的错误,请告诉我。

4 个答案:

答案 0 :(得分:4)

tl; dr

try 
{
    LocalDate ld = 
        LocalDate.parse( 
            "01/23/2021" , 
            DateTimeFormatter.ofPattern( "MM/dd/uuuu" )
        ) 
    ;
}
catch ( DateTimeFormatException e )
{
    … handle faulty input
}

java.time.LocalDateDateTimeFormatException

从不使用可怕的日期时间类,例如CalendarDate。仅使用JSR 310定义的现代 java.time 类。

定义一种格式设置以匹配您的输入。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) ;

将您的输入解析为LocalDate对象。

LocalDate ld = LocalDate.parse( input , f ) ;

如果输入错误,请抛出DateTimeFormatException

try 
{
    LocalDate ld = LocalDate.parse( input , f ) ;
}
catch ( DateTimeFormatException e )
{
    … handle faulty input
}

关于 java.time

java.time框架已内置在Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendarSimpleDateFormat

要了解更多信息,请参阅Oracle Tutorial。并在Stack Overflow中搜索许多示例和说明。规范为JSR 310

Joda-Time项目(现在位于maintenance mode中)建议迁移到java.time类。

您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*类。 Hibernate 5和JPA 2.2支持 java.time

在哪里获取java.time类?

答案 1 :(得分:3)

编辑(添加年度支票)

假设您使用的是Java 8,下面的代码检查是否--

  • 格式正确(MM / dd / yyyy)
  • 如果输入的年份小于当前年份
  • 如果输入的年份大于(当前年份-100)
  • 如果是31天,30天或leap年
  • 输入字符串中是否有意外字符串,除了 整数

导入-import java.text.*;import java.time.*;

逻辑-

 private static boolean checkDate(String dateStr) {

        DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        sdf.setLenient(false);

        try {
          sdf.parse(dateStr);

          int currentYear = Year.now().getValue();
          String str[] = dateStr.split("/");
          int year = Integer.parseInt(str[2]);

          if(year > currentYear || year < currentYear-100){
            return false; 
          }

        } catch (NumberFormatException | ParseException ex){

          return false;  // Returns false if parsing fails (in case of bad input).
        }

        return true; // Returns true for valid date Strings
     }

测试-

        System.out.println(checkDate("02/09/2021")); // Returns false
        System.out.println(checkDate("02/09/2020")); // Returns true
        System.out.println(checkDate("02/09/1900")); // Returns false
        System.out.println(checkDate("02/31/2020")); // Returns false
        System.out.println(checkDate("11/31/2020")); // Returns false
        System.out.println(checkDate("05/23/2020")); // Returns true
        System.out.println(checkDate("abc/23/2020")); // Returns false
        System.out.println(checkDate("05/23/efg")); // Returns false
        System.out.println(checkDate("02/29/2016")); // Leap year. Returns true
        System.out.println(checkDate("02/29/2019")); // Not a Leap year. Returns false

答案 2 :(得分:2)

我使用“ 01/11/2019”运行您的代码,它返回false。

我在checkDate函数中的代码中发现了一些东西。 我要发表评论。

public static boolean checkDate(String date) {
          //1. Target: String date = "MM/dd/yyyy" 
          Calendar cal = Calendar.getInstance();
          int year=0, month=0, day=0;

          int year2;

          year=Integer.parseInt(date.substring(6));
          day=Integer.parseInt(date.substring(3,5));
          month=Integer.parseInt(date.substring(0,2));

          year2=cal.get(Calendar.YEAR);
          //2. this check will in the very beginning for the safety purpose, if the date string length is not 10, it will false, no need to do above work.
          if(date.length() != 10)
            return false;

          if(year==year2||year<=year2-100)
            return true;
         //3. Here is a obviously error, month is from 1 to 12, so change here to else if (month <= 12 && month >= 1)  
         else if(month>12||month<1)
            return true;

         //4. else if(day >= 1 && day <= 31) 
         else if(day<1)
            return true;

         //5. else if(month == 2 && day >= 28)
         else if(month==2&&day>28)
            return true;

         //6. else if((month==1||month==3||month==5||month==7||month==8||month==10||month==12)&&day==31)
         else if((month==1||month==3||month==5||month==7||month==8||month==10||month==12)&&day>31)
            return true; 

         //7. else if((month== 4||month==6||month==9||month==11)&& day ==30)       
         else if((month!=1||month!=3||month!=5||month!=7||month!=8||month!=10||month!=12)&&day>31)
            return true;
         else
            return false;
    }

答案 3 :(得分:1)

您可能有原因,但是我建议您使用SimpleDateFormat类,因为您可以选择模式并根据需要设置日期格式。这是一个非常简单的示例,类似于您发布的内容,因此您可以看看

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
    System.out.println(simpleDateFormat.format(cal.getFirstDayOfWeek()));

    String s = simpleDateFormat.format(cal.getFirstDayOfWeek());
    String [] array = s.split("/");

    int year=Integer.parseInt(array[2]);
    int day=Integer.parseInt(array[1]);
    int month=Integer.parseInt(array[0]);

    if(year > 2000 && year < 2020) {
        //To Do
    }
    if(day <= 31) {
        //To Do
    }
    if(month <= 12) {
        //To Do
    }

输出:

    01/01/1970
相关问题