Java中的日期零验证

时间:2017-09-29 16:33:52

标签: java date

我有一个方法,将Date field作为输入参数。

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

我所做的是如下所示,但我无法在传递零点数的无效日期时收到错误,例如"新日期(0L)"作为inputDate参数。

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

2 个答案:

答案 0 :(得分:2)

Skeet接受的答案是正确的。

TL;博士

input.equals( Instant.EPOCH ) 

java.time

您正在使用现在由java.time类取代的麻烦的旧日期时间类。

Instant类取代Date作为UTC时间轴上的一个时刻,但具有更精细的分辨率纳秒而不是毫秒。

您可以在与尚未更新的旧代码连接到java.time类时进行转换。要转换,请调用添加到旧类的新方法。

Instant instant = myDate.toInstant() ;

检查是否为空。

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

检查那个似乎特别值得关注的从纪元数值零开始。 Instant类有一个常数,因为Unix和Java使用的纪元参考日期时间为零纳秒:1970年的第一个UTC时刻。

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

如果业务规则要求,您可能需要检查最近的日期时间值。

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

生成字符串时考虑时区。对于任何特定时刻,日期和时间在全球范围内因地区而异。

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

您想要的格式恰好是标准ISO 8601格式的“基本”版本。此格式预定义为常量:DateTimeFormatter.BASIC_ISO_DATE

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

答案 1 :(得分:1)

听起来你只是想要:

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

这将检测inputDate是否为空或代表Unix时代。

正如评论中所述:

  • 拒绝单个值有点危险 - 为什么new Date(0)"错误"但是new Date(1)"对"?
  • 这可以防止您接受恰好是Unix纪元的合法输入