以下代码的主要思想是比较两个日期,精度为1分钟。
rc
是参考时间,tc
是测试的时间:
// Checking precision of 1 minute
Calendar upperBound, lowerBound;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
upperBound = (Calendar)rc.clone();
upperBound.add(Calendar.MINUTE, 1);
lowerBound = (Calendar)rc.clone();
lowerBound.add(Calendar.MINUTE, -1);
//Actual values
System.out.println("test "+dateFormat.format(tc.getTime()));
System.out.println("UpperB"+dateFormat.format(upperBound.getTime()));
System.out.println("LowerB "+dateFormat.format(lowerBound.getTime()));
//Tests
System.out.println("test after "+tc.after(lowerBound));
System.out.println("test before "+tc.before(upperBound));
输出如下:
test 05/10/2015 09:43.
UpperB 05/10/2015 09:44.
LowerB 05/10/2015 09:42.
test after false.
test before true.
我很困惑,因为测试日期与下限的Calendar.after()
比较返回false
,其中应该是true
之前打印的日期。
任何想法,也许我做错了什么?
答案 0 :(得分:0)
使用JDK 1.8进行测试:
Calendar tc = Calendar.getInstance();
Calendar rc = Calendar.getInstance();
Calendar upperBound, lowerBound;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
upperBound = (Calendar) rc.clone();
upperBound.add(Calendar.MINUTE, 1);
lowerBound = (Calendar) rc.clone();
lowerBound.add(Calendar.MINUTE, -1);
//Actual values
System.out.println("test " + dateFormat.format(tc.getTime()));
System.out.println("UpperB " + dateFormat.format(upperBound.getTime()));
System.out.println("LowerB " + dateFormat.format(lowerBound.getTime()));
//Tests
System.out.println("test after " + tc.after(lowerBound));
System.out.println("test before " + tc.before(upperBound));
输出:
test 08/11/2015 05:34
UpperB 08/11/2015 05:35
LowerB 08/11/2015 05:33
test after true
test before true