验证具有不同格式的日期列表

Validate a date list with different formats

我有一个要验证的日期列表,我有一个仅适用于单个日期的函数,但我现在想要一个日期列表。

规则:

1) 当列表为空时,我return true

2) 当一个日期无效时,我切换到以下并将其从日期列表中删除

3) 编辑 当所有执行完成后我 return true(如果至少有一个是有效的)或 false(所有都未通过测试)。

编辑:不用这个 isDateValid(String date) ==> isDateValid(List<LString> date)

日期列表:

List<String> dateList= new ArrayList<>();

dateList.add("2016-10-02T04:00:00.000Z");
dateList.add("2017-02-15T14:32:32");
dateList.add("2017-01-23");

函数(只有一个日期):

 public boolean isDateValid(String date ) {
        List<SimpleDateFormat> knownPatterns = new ArrayList<>();
        knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
        knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd"));
        knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
        knownPatterns.add(new SimpleDateFormat("MM/dd/yyyy"));

        for (SimpleDateFormat pattern : knownPatterns) {
            try {
               Date timestamp = pattern.parse(date);
               return true;                
            } catch (ParseException e) {
                continue;
            }
        }
        return false;
    }
your isDateValid method can be modified as follow for list

    public  boolean isDateValid(List<String> list ) {
        //return true if list is null or empty
        if(list==null || list.isEmpty())
            return true;
        List<SimpleDateFormat> knownPatterns = new ArrayList<>();
        knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
        knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd"));
        knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
        knownPatterns.add(new SimpleDateFormat("MM/dd/yyyy"));
        //counter to keep counting valid dates
        int validCount=0;
        boolean flag=false;
        Iterator<String> itr=list.iterator();
        String date;
        while(itr.hasNext()){
            date=itr.next();
        for (SimpleDateFormat pattern : knownPatterns) {
            try {
                pattern.parse(date);
                validCount++;
                flag=true;
               break;               
            } catch (ParseException e) {
                continue;
            }
        }
        if(!flag)
            itr.remove();
        else
            flag=true;
        }
        //if there were valid dates in list return true else return false
        return validCount>0?true:false;
    }

我使用了迭代器,因为当你遍历一个列表时,你不能只删除一个项目然后继续

 public boolean isDateValid(ArrayList<String> dates ) {
        if(dates.isEmpty()) return true;
        List<SimpleDateFormat> knownPatterns = new ArrayList<>();
        knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
        knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd"));
        knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
        knownPatterns.add(new SimpleDateFormat("MM/dd/yyyy"));
        //Iterator usage is for deleting
        for (Iterator<String> itarator = dates.iterator() ; iterator.hasNext()){
            String date = iterator.next();
            for (int i = 0; i< knownPatterns.size(); i++) {
                try {
                    Date timestamp = knownPatterns.get(i).parse(date);
                    return true;                
                } catch (ParseException e) {
                    if(i == knownPatterns.size()-1){
                    iterator.remove();
                    }
                    continue;
                }
            }
        }
        return false;
    }

只需重用您现有的函数并添加另一个提供列表所需逻辑的函数。

public boolean isDateValid(List<String> dates) {
    if (dates == null || dates.isEmpty()) {
        return true;
    }

    for (Iterator<String> iter = dates.iterator(); iter.hasNext(); ) {
        String date = iter.next();
        if (!isDateValid(date)) {
            iter.remove();
        }
    }

    // return true if at least one date is valid? 
    return !dates.isEmpty();
}

或者更好,如果您已经在使用 Java 8 并且想使用 Collection 和 Lambdas

的新方法
public boolean isDateValid(List<String> dates) {
    if (dates == null || dates.isEmpty()) {
        return true;
    }

    dates.removeIf(date -> !isDateValid(date));

    // return true if at least one date is valid?
    return !dates.isEmpty();
}

你可以写一个class来验证:

class DateValidator {
    private String format;
    public DateValidator(String format) {
        this.format = format;
    }
    boolean validDate(String toParse) {
        try {
            new SimpleDateFormat(format).parse(toParse);
        } catch (ParseException ex) {
            return false;
        }
        return true;
    }
    static boolean validDate(List<DateValidator> validators, String toParse) {
        return validators.stream().anyMatch(v -> v.validDate(toParse));
    }
}
// and this is how you use it:
List<String> toValidate = createList(); // your list
List<String> validFormats = createValidFormats();
validator = formats.stream().map(DateValidator::new) // now we have a validator stream
    .collect(Collectors.reducing(Predicate::or)) // now all of them are ORed
    .orElse(s -> false); // default is not a valid format (?)
toValidate.removeIf(validator);

这是干净的代码,因为 DateValidator class 是可重用的,并且具有清晰的单一用法。也许流需要习惯,YMMV。 如果您经常使用此验证,您还可以创建一个复合验证器 class:

class CompositeDateValidator {
    private Predicate<String> validator;
    public CompositeDateValidator(Collection<String> formats) {
        // or use getters/setters, or an addFormat method
        validator = formats.stream().map(DateValidator::new) // now we have a validator stream
            .collect(Collectors.reducing(Predicate::or)) // now all of them are ORed
            .orElse(s -> false); // default is not a valid format (?)
    }
    public boolean validate(String toValidate) {
        return validator.test(toValidate);
    }
}
// and then use it like this
List<String> validFormats = createValidFormats();
// this could be a member or Singleton somewhere
CompositeValidator validator = new CompositeValidator(validFormats);

List<String> toValidate = createList().removeIf(date -> !validator.validate(date));

这可能设计过度了,但我在查找如何做到这一点方面学到了很多东西;)