user1954746
user1954746

Reputation: 41

Validating a date in Java

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

Upvotes: 4

Views: 50940

Answers (8)

Shivraj Sendhav
Shivraj Sendhav

Reputation: 1

System.out.println("Please Enter Event End Date Please Enter Date in format MM/dd/YYYY");
String eventEndDateString = sc.next();
Date eventEndDate = null;
try {
    eventEndDate = simpleDateFormat.parse(eventEndDateString);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println(eventEndDate);

Upvotes: 0

Anonymous
Anonymous

Reputation: 86276

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.

Upvotes: 1

duffymo
duffymo

Reputation: 308763

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.

Upvotes: 11

mcacorner
mcacorner

Reputation: 1274

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.

Upvotes: 0

Anders R. Bystrup
Anders R. Bystrup

Reputation: 16060

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

Upvotes: 3

Roy
Roy

Reputation: 44288

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...

Upvotes: 1

fge
fge

Reputation: 121710

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.

Upvotes: 1

PermGenError
PermGenError

Reputation: 46408

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;
    }
}

Upvotes: 0

Related Questions