How to check if the Date conforms to a specific DateFormat without using Exception?

回眸只為那壹抹淺笑 提交于 2021-02-10 12:50:16

问题


I am aware that parse() can be used for knowing if the valid date conforms to a specific format. But that throws exception in case of a failure. I wanted just to verify if the date is of a specific format. Especially I need a boolean result from this comparison. How to achieve that in Java?


回答1:


I am wondering why nobody here knows following standard validation using ParsePosition. Programming based on exception logic is more or less evil.

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(false);
ParsePosition pp = new ParsePosition(0);
java.util.Date d = sdf.parse("02/29/2015", pp);

if (d == null) {
    System.out.println("Error occurred at position: " + pp.getErrorIndex());
    return false;
} else {
    return true; // valid
}

Note that it is important to use the strict mode!

A little bit out of scope of the question but interesting:

The new java.time-library (JSR-310) does force the user to code against exceptions - a clear regression compared with 'SimpleDateFormat`. The problem of catching exceptions is generally bad performance which can be relevant if you parse bulk data with lower quality.




回答2:


Unless you want to write regular expression which you can match against your date format I am afraid there is no other way than catching ParseException.




回答3:


public static Scanner s;

public static void main(String[] args) {
    System.out.println(checkDateFormat("2000-01-01"));
}

// Checks if the date meets the pattern and returns Boolean
// FORMAT yyyy-mm-dd RANGE : 2000-01-01 and 2099-12-31
public static Boolean checkDateFormat(String strDate) {

    if (strDate.matches("^(19|20)\\d\\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$")) {
        return true;
    } else {
        return false;
    }
}

This solution right here uses Regex Patterns to validate the date format (No Exceptions needed as there is no need for any because you are not using the SimpleDateFormat Parse() method). For more information/help about regular expressions and dates visit http://www.regular-expressions.info/dates.html.




回答4:


Something like this if you want to achive that in java core.

 private static final PARSER = new SimpleDateFormat(FORMAT);
 boolean isParsable(String date){       
   try {
       PARSER.parse(date);
   } catch (Exception ex) {
     return false;
   }
   return true;
 }


来源:https://stackoverflow.com/questions/35626873/how-to-check-if-the-date-conforms-to-a-specific-dateformat-without-using-excepti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!