gpt4 book ai didi

java - 日期比较失败

转载 作者:行者123 更新时间:2023-12-02 07:04:13 27 4
gpt4 key购买 nike

我编写了一个注释来检查日期是否是将来的日期,这是 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 吗?

最佳答案

您的date变量实际上是一个Timestamp。来自 Timestamp javadoc :

The Timestamp.equals(Object) method never returns true when passed a value of type java.util.Date because the nanos component of a date is unknown.

javadoc 还建议不要在需要 Date 的地方使用 Timestamp,即使 Timestamp 继承自 Date

关于java - 日期比较失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16296299/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com