Java Calendar.before()返回错误的值
下面代码的主要思想是以1分钟的精度比较两个日期 rc是参考时间,tc是测试时间:Java Calendar.before()返回错误的值,java,Java,下面代码的主要思想是以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); lowe
// 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
有什么想法吗,也许我做错了什么?用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
什么是rc和tc?它们的定义是什么?你试过不同的格式吗?这些时间是下午还是上午?当打印每个日历的getTimeInMillis时,你会看到什么?正如@toniedzwiedz所问的。。。rc已克隆,但tc已测试。无法使用Calendar rc=Calendar.getInstance再现您的问题;日历tc=日历rc.clone;,那么这两个检查都是正确的。请不要试图在注释中添加代码。向问题本身添加信息,并正确设置格式。这不是答案。这仍然不是答案。在Java 8上为我工作可能会被添加为问题的注释,而不是答案。你想要像他是骗子一样的答案吗?不,StackOverflow需要一个实际回答问题或提供问题解决方案的答案。如果没有这样的答案,那么就不应该发布任何东西作为答案。答案他提供的代码是可以的-也可以是答案,这样他就可以在代码的其他地方搜索bug