I’ve been doing some date math at work and I came across something I thought was wack.
Check this out:
Calendar cal1 = Calendar.getInstance(); Thread.sleep(500); Calendar cal2 = Calendar.getInstance(); Thread.sleep(500); Date now = new Date(); System.out.println(cal1.before(cal2)); System.out.println(cal1.before(now));
What do you think this snippet prints (It compiles, I promise!)?
Looking at the code, it shows that we are getting three snapshots in time, waiting half a second between snapshots, and assigning those values to
now, respectively. I put in the Thread.sleep() to illustrate the point more clearly. The first print statement compares the first and second snapshots in time, returning true if the first is before the second. The second print statement returns true if the first is before the third snapshot.
Logically, we would expect both print statements to prints true. However, this outputs:
But, how could the first snapshot be before the second snapshot but not the third?
Putting up the javadocs, gives us our answer. The Calendar before and after methods always returns false if you don’t pass it a Calendar object. Why? I have no idea. Why not just have the method signature take a Calendar object? I mean, I guess this allows you to extend Calendar to be able to call after/before on whatever kind of classes you want to support…but does it really make sense to compare a Calendar to a Monkey class? This is what I call a Java WTF.