0

我写了一个注释来检查一个日期是否在未来,这是 ivValid 实现:

public boolean isValid( Date date, ConstraintValidatorContext constraintValidatorContext )
    {
        String message = null;

        Date todayWithoutTime = DateUtils.truncate( Calendar.getInstance().getTime(), Calendar.DAY_OF_MONTH );

        if ( ( date == null ) || ( !date.after( todayWithoutTime ) && !date.equals( todayWithoutTime ) ) )
        {
            message = "{validation.definition.notfutureDate}";
        }

        if ( message != null )
        {
            constraintValidatorContext.disableDefaultConstraintViolation();
            constraintValidatorContext.buildConstraintViolationWithTemplate( message ).addConstraintViolation();
        }

        return message == null;
    }

我有以下日期对象:

date    Timestamp  (id=157) 
    cdate   Gregorian$Date  (id=192)    
        cachedFixedDateJan1 734869  
        cachedFixedDateNextJan1 735234  
        cachedYear  2013    
        daylightSaving  3600000 
        dayOfMonth  30  
        dayOfWeek   3   
        era null    
        forceStandardTime   false   
        fraction    0   
        hours   0   
        leapYear    false   
        locale  null    
        millis  0   
        minutes 0   
        month   4   
        normalized  true    
        seconds 0   
        year    2013    
        zoneinfo    ZoneInfo  (id=212)  
        zoneOffset  7200000 
    fastTime    1367272800000   
    nanos   0

todayWithoutTime    Date  (id=173)  
    cdate   Gregorian$Date  (id=185)    
        cachedFixedDateJan1 734869  
        cachedFixedDateNextJan1 735234  
        cachedYear  2013    
        daylightSaving  3600000 
        dayOfMonth  30  
        dayOfWeek   3   
        era null    
        forceStandardTime   false   
        fraction    0   
        hours   0   
        leapYear    false   
        locale  null    
        millis  0   
        minutes 0   
        month   4   
        normalized  true    
        seconds 0   
        year    2013    
        zoneinfo    ZoneInfo  (id=212)  
        zoneOffset  7200000 
    fastTime    1367272800000

date.getTime() 给出 13672728000000,todayWithoutTime.getTime() 给出 13672728000000。

有人可以解释一下为什么检查!date.equals(todayWithoutTime)返回 true 吗?

4

1 回答 1

2

你的date变量实际上是一个Timestamp. 从Timestampjavadoc

Timestamp.equals(Object) 方法在传递 java.util.Date 类型的值时永远不会返回 true,因为日期的 nanos 组件是未知的。

javadoc 还建议不要使用TimestampwhereDate预期,即使Timestamp继承自Date.

于 2013-04-30T09:33:04.320 回答