我遇到了Calendar的after方法的奇怪错误。下面的代码占用了当前时间,并且应该在明天的同一时间返回。使用当前时间运行代码时会发生错误。有什么想法正在发生什么?
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Vector;
public class NextDateTest {
public static void main(String[] args) {
Vector<Object> setup = new Vector<Object>();
Calendar dt = Calendar.getInstance();
SimpleDateFormat hour = new SimpleDateFormat("HH");
SimpleDateFormat minute = new SimpleDateFormat("mm");
setup.add(hour.format(dt.getTime()));
setup.add(minute.format(dt.getTime()));
for(int a=0; a<11; a++){
dateTest(setup);
}
}
static void dateTest(Vector<Object> vec){
Calendar dt = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm");
System.out.println("Old time:" + format.format(dt.getTime()));
dt.set(Calendar.HOUR_OF_DAY, Integer.valueOf((String) vec.elementAt(0)));
dt.set(Calendar.MINUTE, Integer.valueOf((String) vec.elementAt(1)));
System.out.println(Calendar.getInstance().after(dt));
if(Calendar.getInstance().after(dt)){
dt.add(Calendar.DAY_OF_YEAR, +1);
}
System.out.println("New time:" + format.format(dt.getTime()));
}
}
结果:
Old time:12/19/2011 10:38
true
New time:12/20/2011 10:38
Old time:12/19/2011 10:38
false
New time:12/19/2011 10:38
Old time:12/19/2011 10:38
true
New time:12/20/2011 10:38
Old time:12/19/2011 10:38
false
New time:12/19/2011 10:38
Old time:12/19/2011 10:38
true
New time:12/20/2011 10:38
Old time:12/19/2011 10:38
false
New time:12/19/2011 10:38
Old time:12/19/2011 10:38
false
New time:12/20/2011 10:38
Old time:12/19/2011 10:38
false
New time:12/19/2011 10:38
Old time:12/19/2011 10:38
true
New time:12/20/2011 10:38
Old time:12/19/2011 10:38
false
New time:12/19/2011 10:38
Old time:12/19/2011 10:38
true
New time:12/20/2011 10:38
答案 0 :(得分:3)
这不是一个错误。 Calendar.after(...)
执行严格不等式,Calendar
仅存储毫秒精度。 (就此而言,我甚至不确定它是否保证在所有系统上精确到毫秒;我相信有些系统不会让软件访问那么小的时间增量。但是毫秒是典型的。)因此,如果dateTest(...)
对Calendar.getInstance()
的两次调用在同一毫秒内发生,那么Calendar.after(...)
将返回false
,dt.add(Calendar.DAY_OF_YEAR, +1)
将不会进行。