Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating a date in java

I am using NetBeans IDE 7.2. I have two seperate 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 iof thing I've been taught to use is Date Formmater but not sure whether this is appropriate here? if so wouldn't know how to use it

like image 486
user1954746 Avatar asked Dec 04 '22 00:12

user1954746


2 Answers

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.

like image 192
duffymo Avatar answered Dec 19 '22 14:12

duffymo


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

like image 28
Anders R. Bystrup Avatar answered Dec 19 '22 14:12

Anders R. Bystrup