简体   繁体   中英

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

It sounds like you just want:

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

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

As noted in the comments though:

  • Rejecting a single value is kinda dangerous - why is new Date(0) "wrong" but new Date(1) "right"?
  • This prevents you accepting legitimate input that happens to be the Unix epoch

The accepted Answer by Skeet is correct.

tl;dr

input.equals( Instant.EPOCH ) 

java.time

You are using troublesome old date-time classes that are now supplanted by the java.time classes.

The Instant class takes the place of Date as a moment on the timeline in UTC but with a finer resolution of nanoseconds rather than milliseconds.

You can convert when interfacing with legacy code not yet updated to java.time classes. To convert, call new methods added to the old classes.

Instant instant = myDate.toInstant() ;

Check for null.

if ( null == input ) {
    throw new IllegalArgumentException( "Received invalid input: null." ) ;
}

Check for that count-from-epoch value zero that seems to be of special concern to you. The Instant class has a constant for that, for a count of zero nanoseconds from the epoch reference date-time used by Unix and Java: first moment of 1970 in UTC.

if ( input.equals( Instant.EPOCH ) ) {
    throw new IllegalArgumentException( "Received invalid input: Instant.EPOCH. Input must be later than 1970-01-01T00:00:00Z." ) ;
}

You might want to check for recent date-time values, if required by your business rules.

if ( input.isBefore( Instant.now() ) ) {
    throw new IllegalArgumentException( "Received invalid input. Input must not be in the past." ) ;
}

When generating a string take into account time zone. For any given moment, the date and the time-of-day vary around the globe by zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Your desired format happens to be the "basic" version of a standard ISO 8601 format. This format is predefined as a constant: DateTimeFormatter.BASIC_ISO_DATE .

String output = zdt.format( DateTimeFormatter.BASIC_ISO_DATE ) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM