根据附加参数验证日期范围

Validate date range based on additional parameter

我正在处理需要根据第三个参数验证两个日期之间差异的需求。

要求:

我写了下面的代码,但它并没有给出完美的结果testing.Please帮助我更正这段代码。

public static boolean validateDateRange(String startDate,String EndDate,String extension){  
        if(startDate.equals("NA")||EndDate.equals("NA")){
            return true;
        }
        else{
            boolean x=false;
            if(extension.equalsIgnoreCase("Y")){
                x=true;
            }
                Date d1 = null;
                Date d2 = null;
                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
                try {
                    d1 = format.parse(startDate);
                    d2 = format.parse(EndDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                long diff = d2.getTime()- d1.getTime();//in Milli seconds
                long numOfDays = diff/(1000*60*60*24);
                System.out.println(numOfDays);
                if(numOfDays >14&&(x&&numOfDays>28)){
                    return false;
                }
                else{
                    return true;
                }
        }

    }

基本上,只是删除了一些多余的 if。但是,您应该重新考虑发生异常时会发生什么。这种情况下继续处理意义不大。在这种情况下,return 值可能应该是 true,因为您不希望任何人因系统错误而被罚款。甚至可能重新抛出异常?

public static boolean validateDateRange(String startDate,String EndDate,String extension){  
    if(startDate.equals("NA")||EndDate.equals("NA")){
        return true;
    }

    boolean x = extension.equalsIgnoreCase("Y");

    Date d1 = null;
    Date d2 = null;
    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
    try {
        d1 = format.parse(startDate);
        d2 = format.parse(EndDate);
        long diff = d2.getTime()- d1.getTime();//in Milli seconds
        long numOfDays = diff/(1000*60*60*24);
        System.out.println(numOfDays);

        return !((!x && numOfDays > 14) || numOfDays > 28);
    } catch (ParseException e) { // maybe rethrow exception?
        e.printStackTrace();
    }

    return true;
}