This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hello all. Hope this isnt a dumb question. I'm writing code to compare two dates and list the difference in months between dates.
works for the year but i keep getting the same answer for the months. example june 1980 and then the date to compare it to may 1982
the answer will be 23 months. but my code would return 24.
then if i enter the same for the first date then January 1984 then it would be 42 but mine will return 48
I commented where i think i went wrong but if anyone can tell me where i went wrong please let me know. its driving me crazy.
"Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do." -- Steve Jobs
Just scanning through the code, I could spot one potential problem: In the getMonth() method, you are taking String "mon" as an argument, but then you are not using it anywhere in the method, instead you are comparing the class-level "month" variable value with String month names. So, the value "newMonth" obtained in the main method is getting lost in the process, since the months you compare are always the same (i.e. both are values got from class level variable "month"). This is probably the reason why your code only finds difference in the years entered, and then multiplies it by 12 and gives the answer in number of months and you are getting answers like 12 months, 24 months, 48 months etc.
Other than this, in the monthsUtil method, I find the logic to calculate the "diff" a bit weird. For example, if you choose January 2000 and June 2001 as your two dates, then the expression
would give the answer as 7, which is incorrect. I guess you would need to work on this logic a bit.
Another question is why are you asking for the "day" only once? If you want to compare the dates by considering the day-of-month, then you should also ask for the day value to be compared. Then you would also need to modify the logic for calculating the "diff" (mentioned in my previous reply) by considering the day along with the month and the year values.