我遇到了日曆後的方法怪異的錯誤。下面的代碼需要當前時間,並且應該在同一時間返回明天的日期。當您使用當前時間運行代碼時,會發生此錯誤。任何想法發生了什麼?Java日曆的方法返回不一致的結果 - 任何想法?
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
爲什麼你要傳遞對象的矢量,解析字符串等?你的測試代碼看起來比它應該更復雜。你爲什麼要執行11次? – 2011-12-19 16:02:27
你知道日曆有一個'.add()'方法嗎? – fge 2011-12-19 16:06:30
@fge:他或她在說,所以是的,我會說他的確如此。 :-) – ruakh 2011-12-19 16:11:33