gpt4 book ai didi

java - 为什么 Calendar before() 方法对于相同的日期返回 true

转载 作者:行者123 更新时间:2023-12-01 16:53:50 24 4
gpt4 key购买 nike

我根据 dueDate 字段与当前日期的比较来设置颜色字段。 dueDate 是一种 SQL 日期类型。我的问题是,当我传入当前日期时,Calendar.before() 方法表示该日期在当前日期之前。我的代码是:

private String getDateDueColor(Date dateDue) {
Calendar today = Calendar.getInstance();
today.setTime(new java.sql.Date(Calendar.getInstance().getTime().getTime()));
Calendar dueDate = Calendar.getInstance();
dueDate.setTime(dateDue);
if(dueDate.before(today)){
return RED;
}else{
return NORMAL;
}
}

我设置了一个断点并比较了 dueDatetoday,每个对象的 cdate 字段中的所有信息看起来都相同,但是dueDate.before(today) 仍然返回 true。任何帮助将不胜感激!

最佳答案

你确定它们相等吗? DateCalendar 的方法 equals 表示它们表示相同的时间值(距纪元的毫秒偏移量)。请参阅javadocs for Calendar.equals method :

Compares this Calendar to the specified Object. The result is true if and only if the argument is a Calendar object of the same calendar system that represents the same time value (millisecond offset from the Epoch) under the same Calendar parameters as this object.

before method docs states compareTo 用于确定一个日历实例是否在另一个日历实例之前。同样,compareTo 使用毫秒精度。来自 the docs :

Compares the time values (millisecond offsets from the Epoch) represented by two Calendar objects.

替代方案是:

  1. 如果您必须使用日历,请创建新实例,对其使用 clear 方法,然后使用 set method 设置值(年、月、小时、分钟、秒)。 .
  2. 使用新的 java.time API并选择一些更能代表您想要的类型(也许 java.time.LocalDate )
  3. 使用Joda Time如果您无法转到 Java 8。

关于java - 为什么 Calendar before() 方法对于相同的日期返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35510482/

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