4

I am using NetBeans IDE 7.2. I have two separate classes newDateTest.java and newDateMethod.java, I am currently using my method class to validate a date from a user input which I have used in my test class.

So far in my test class I have the following:

try
{
    Prompt ="please enter a date in the format dd-mm-yyyy";
    System.out.println(Prompt);
    String inputDate = in.next();
    isValid = newDateMethod.validDate(input, input, input);
    if (isValid){
        System.out.println("VALID DATE");
        
    } else {
        System.out.println("INVALID DATE");
    
    }
    
} catch (ArrayIndexOutOfBoundsException oob) {
    System.out.println(oob);
}

However I have no idea how to validate the date in my method class as I am fairly new to Java.

Can anyone come to a solution? The sort of thing I've been taught to use is Date Formatter but I'm not sure whether this is appropriate here? If so, I wouldn't know how to use it

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
user1954746
  • 41
  • 1
  • 1
  • 2
  • 2
    Your question has attracted a lot of answers which recommend the SimpleDateFormat class. Be careful with this. To give two examples, the parse() method cannot detect errornous months (i.e. 13th month) and the format for year can be burst with longer years. You can't *just validate* a Date with this class. It depends on *what* you want to validate. – 8bitjunkie Dec 13 '13 at 13:18
  • See also [this answer](https://stackoverflow.com/questions/226910/how-to-sanity-check-a-date-in-java) for more ways to validate a date in Java. – Matthias Braun Jan 23 '23 at 09:28

7 Answers7

11

Like this:

Date date = null;
String inputDate = "07-01-2013";
try {
    DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
    formatter.setLenient(false);
    date = formatter.parse(inputDate);
} catch (ParseException e) { 
    e.printStackTrace();
}

Updated on 13-Jul-2021:

I heartily agree with Ole V.V.'s comment below. All Java and Kotlin developers should prefer the java.time package.

I'll add a more modern example when time permits.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • 1
    it is wrong !! If instead of "07-01-2013" your input will be "07-01-017" or "07-01-2ooo" you would not get exception, but the format is wrong – magulla Mar 28 '17 at 16:26
  • 1
    For new readers to this question and/or this answer I recommend we don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jul 13 '21 at 12:24
3

Have a look at SimpleDateFormat.parse(...) and do remember to surround with try-catch.

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
1

The standard JDK class for that is SimpleDateFormat:

DateFormat fmt = new SimpleDateFormat("yourformathere");

// use fmt.parse() to check for validity

Alternatively, I'd recommend using Joda Time's DateTimeFormat.

fge
  • 119,121
  • 33
  • 254
  • 329
  • 1
    If you use "dd/MM/yyyy" as a pattern with SimpleDateFormat and input the date as "13/13/2013" for example, the parse method will return a java.util.Date with the date 13/01/2014. Beware and DO NOT use the standard JDK classes below Java 8 for Date calculation. – 8bitjunkie Dec 13 '13 at 13:10
1

Rather than relying on exceptions which tend to have a small performance overhead, you can also use the DateValidator from the Apache commons routines package like this:

if (DateValidator.getInstance().validate(inputDate, "dd-MM-yyyy") != null) {
  // Date is valid
}
else {
  // Date is invalid
}

Small disclaimer though, I haven't looked at the implementation of the validate method and I'm not sure if it uses for instance the SimpleDateFormat...

Roy
  • 43,878
  • 2
  • 26
  • 26
  • 2
    Warning: Date testDate = DateValidator.getInstance().validate("25/13/2013", "dd/MM/yyyy") correctly identifies that 13 is not a valid month but Date testDate = DateValidator.getInstance().validate("25/13/2013456", "dd/MM/yyyy"); returns as a valid date despite the mask only allowing 4 characters. – 8bitjunkie Dec 13 '13 at 13:15
1

java.time

I recommend that you use java.time, the modern Java date and time API, for your date work. It also gives you much preciser validation than the old SimpleDateFormat class used in some of the other answers.

    String[] exampleInputStrings = { "07-01-2013", "07-01-017",
            "07-01-2ooo", "32-01-2017", "7-1-2013", "07-01-2013 blabla" };
    
    for (String inputDate : exampleInputStrings) {
        try {
            LocalDate date = LocalDate.parse(inputDate, DATE_FORMATTER);
            System.out.println(inputDate + ": valid date: " + date );
        } catch (DateTimeParseException dtpe) {
            System.out.println(inputDate + ": invalid date: " + dtpe.getMessage());
        }
    }

Output from my example code is:

07-01-2013: valid date: 2013-01-07
07-01-017: invalid date: Text '07-01-017' could not be parsed at index 6
07-01-2ooo: invalid date: Text '07-01-2ooo' could not be parsed at index 6
32-01-2017: invalid date: Text '32-01-2017' could not be parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): 32
7-1-2013: invalid date: Text '7-1-2013' could not be parsed at index 0
07-01-2013 blabla: invalid date: Text '07-01-2013 blabla' could not be parsed, unparsed text found at index 10

For a good validation you should probably add a range check. Use the isBefore and/or the isAfter method of LocalDate.

Also if you are going to do anything with the date more than validating it, you should keep the LocalDate from the parsing around in your program (not the string).

Oracle tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

You should use SimpleDateFormat.parse(String) method. if the passed date is of wrong format it throws an exception in which case you return false.

public boolean validateDate(String date) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    try {
        sdf.parse(date);
        return true;
    }
    catch(ParseException ex) {
        return false;
    }
}
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0

One can use joda-time.

DateTimeFormat.forPattern(INPUTED_DATE_FORMAT);
//one can also use it with locale
DateTimeFormat.forPattern(USER_DATE_FORMAT).withLocale(locale);
fmt.parseDateTime(INPUTED_DATE);

If parseDateTime throw IllegalArgumentException then date is not valid.

mcacorner
  • 1,304
  • 3
  • 22
  • 45