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 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.
Have a look at SimpleDateFormat.parse(...)
and do remember to surround with try-catch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With