0

I am working on a project where I need to validate multiple dates based on length and patterns. I am using simple date format and found many issues with that. My requirement is to strictly allow if date string matches "yyyy/MM/dd" and strictly 10 characters.

The below code is not giving expected results for various testing input strings.

public static boolean checkformat(String dateString){
        boolean flag = false;
        Date d1 = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        format.setLenient(false);
        try {
            d1 = format.parse(dateString);
            flag=true;
        } catch (ParseException ex) {
            ex.printStackTrace();
            return false;
        }
        return flag;
    }

the above code is returning "true" for various inputs like "99/03/1" (should be 0099/03/01) and 99/1/1( should be 0099/01/1). Since the input strings are not coming from a from so I cant perform validations before passing them to this method. Please suggest any implementation which should act very strict towards the dateformat("yyyy/MM/dd").

Kiran
  • 921
  • 1
  • 11
  • 23
  • I have tried that implementation and its not working as expected for the above mentioned inputs . – Kiran Feb 13 '16 at 06:34

4 Answers4

1

I suggest that you should try to validate date with regex before format it.

user below code for validate

public static boolean checkformat(String dateString){
        boolean flag = false;
        Date d1 = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        format.setLenient(false);
        try {
             if (dateString.matches("([0-9]{4})/([0-9]{2})/([0-9]{2})")) { // use this regex
               d1 = format.parse(dateString);
               flag=true;
             }
        } catch (ParseException ex) {
            ex.printStackTrace();
            return false;
        }
        return flag;
    }
Piyush Ghediya
  • 1,754
  • 1
  • 14
  • 17
  • Thanks for suggestion..Can we override simpledateformat method with above code. Because I have to make this check at many places in my project. and I am validating multiple dates inside some methods .Its bit difficult to add this check for each date. But if overriding is not possible I will go with your solution..Thanks – Kiran Feb 13 '16 at 06:49
  • in this case u can create one your own custom method which is return you validation as well date format. in this method u can use above code. this might help you. – Piyush Ghediya Feb 13 '16 at 09:29
0

Okay, first: You know what format you're expection. So why just parse it and catch an exception rather than checking preconditions ?

if(dateString.size() > 10) {
...

What you are actually doing is not checking your input format but rather parsing it - though the method is not expressing this contract - so if your method is just for checking you could: 1. Use a regex 2. ... ? I know that are quiet a lot of answers on the net which propose using SimpleDateFormat, but - to be frank -they are wrong. If I am expecting a given format, e.g. as I know that conversions have been made on some user input, I can start parsing a string, and considering that something may have gone wrong, catch the exception. If I don't know which format is passed to me, I am at the validation layer and this layer should not try to perform a conversion but rather proof that the conversion would be valid.

Peter
  • 1,769
  • 1
  • 14
  • 18
0

You could try using the new java.time package from Java 8 and later. You could use it as so to replace the SimpleDateFormat:

public static boolean checkformat(String dateString){
    boolean flag = false;

    try {
        TemporalAccessor ta = DateTimeFormatter.ofPattern("yyyyMMdd").parse(strDate);
        flag=true;
    } catch (DateTimeParseException ex) {
        ex.printStackTrace();
        return false;
    }
    return flag;
}

This would also limit the values from making no sense (e.g. month value being 18).

Benjamin Lowry
  • 3,730
  • 1
  • 23
  • 27
0
String[] removeSlashes=new String[3];
removeSlashes = enteredDate.split("/");

if(removeSlashes[0].length()!=4)
     throw new IncorrectDateFormatException(); // user defined exception
if(removeSlashes[1].length()!=2)
     throw new IncorrectDateFormatException();
if(removeSlashes[2].length()!=2)
     throw new IncorrectDateFormatException();

//Then use SimpleDateFormat to verify
Aayush Rohatgi
  • 118
  • 1
  • 10