I’ve come across a weird bug with the Calendar’s after method. The code below takes the current time and should return tomorrow’s date with the same time. The bug happens when you run the code with the current time. Any ideas what’s going on?
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()));
}
}
Results:
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
It’s not a bug.
Calendar.after(...)performs a strict inequality, andCalendaronly stores millisecond precision. (For that matter, I’m not even sure if it’s guaranteed to be accurate to the millisecond on all systems; I believe some systems don’t give software access to time-deltas that small. But milliseconds are typical.) So ifdateTest(...)‘s two calls toCalendar.getInstance()occur within the same millisecond, thenCalendar.after(...)will returnfalse, anddt.add(Calendar.DAY_OF_YEAR, +1)will not be performed.