0% found this document useful (0 votes)
49 views2 pages

Understanding Java Calendar API Bugs

The document discusses how comparing Calendar objects to Date objects in Java can lead to unexpected results. It shows code examples where a Calendar set to 11:51am is compared to a Date parsed as "2016-03-26 15:04:04" using after, before, and equals, but each time it prints 3 instead of the expected 2. This is because Calendar comparison methods treat the Date as a generic Object rather than a Calendar, so the expressions always return false.

Uploaded by

NISHANT MODI
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views2 pages

Understanding Java Calendar API Bugs

The document discusses how comparing Calendar objects to Date objects in Java can lead to unexpected results. It shows code examples where a Calendar set to 11:51am is compared to a Date parsed as "2016-03-26 15:04:04" using after, before, and equals, but each time it prints 3 instead of the expected 2. This is because Calendar comparison methods treat the Date as a generic Object rather than a Calendar, so the expressions always return false.

Uploaded by

NISHANT MODI
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Javas tricky calendar and date APIs

A silly mistake can lead to a big bug, that is one common thing which we all from the
programing world know.

Look at the below program

Calendar cal = [Link]();


[Link](Calendar.HOUR_OF_DAY, 11);
[Link]([Link],51);
Date fromDate = dateFromString("2016-03-26 15:04:04", "yyyy-MM-dd HH:mm:ss");
if ([Link](fromDate))
{
[Link]("2");
}else{
[Link]("3");
}

What do you guess what will be printed , I guess you are guessing 2 but no you are wrong

ok let me give you one more chance


if ([Link](fromDate))
{
[Link]("2");
}else{
[Link]("3");
}

Now , guessing 2 no this time also 3

ok , try this

if ([Link](fromDate))
{
[Link]("2");
}else{
[Link]("3");
}

but this time also it is 3.

Surprised by the results , want to know why ??

Because of the implementation of Calendar class.


the methods after , before are meant for Calendar object but using Object as an input and then
checking the the Object instance of Calender or not,
So the expression written in if will always return false.

You might also like