Ramesh KC Ramesh KC - 3 years ago 176
Java Question

Date Zero Validation In Java

I have a method taking

Date field
as a input parameter.

public static String formatDate(Date inputDate) {
// if user send the date with inputDate= new Date(00000000) or new Date(0L) because it is Java default date.
I have to send the exception error with message Invalid date.

What I did is something as below, But I am unable to get the error while passing the invalid date of zero count-from-epoch like "new Date( 0L )" as inputDate parameter.

public static String formatDate(Date inputDate) {
if (null == inputDate)
throw new FieldFormatException("Empty date field.");

try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
return formatter.format(inputDate);
} catch (Exception ex) {
throw new FieldFormatException("Exception in formatting date field." + ex);

Answer Source

It sounds like you just want:

if (inputDate == null || inputDate.getTime() == 0L)

That will detect if inputDate is null or represents the Unix epoch.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download