I'm trying to write a program that computes the number of days between two dates. Can anyone suggest how i can achieve this. I'm quite sure I'm supposed to use the Calendar class. Thanks in advance.
That doesn't compare the days; that compares the time in milliseconds after casting it to int. No idea why you did that cast anyway. Without it you should be very close, except if c1's hour would be one larger than c2's hour then you would get one day less.
Anyway, to compare if two dates are the same date you need to check two or three fields:
1) are the year, the month and the day of month the same.
2) are the year and day of year the same.
Varun Gokulnath wrote:I'm trying to write a program that computes the number of days between two dates. Can anyone suggest how i can achieve this. I'm quite sure I'm supposed to use the Calendar class. Thanks in advance.
Are you "quite sure [you're] supposed to use the Calendar class" because you think you need to, or because you were told to?
There's a big difference, because you DON'T need a Calendar to compute the number of days between two dates - at least not if they're java.util.Date's - and actually it probably muddies the waters.
Furthermore, you don't even need to "estimate" it, viz from your own code:The method returns an extremely accurate computation of the number of days difference, which you can then truncate or round or convert to a smaller unit any way you see fit.
NOTE: The second thing that has been discussed here (seeing whether two dates are on the same day) is something completely different, because that is a comparison of WALL-CLOCK times - and for that, you DO need a Calendar ... and possibly an explicit timezone.
Isn't it funny how there's always time and money enough to do it WRONG?
What stage are you at with your code? Could you show us what you have done so far? Winston makes a good point regarding Calendar. Is the starting point for your work dates which are entered by a user / read from some data source or does the code simply have to calculate the difference in days between 2 random dates?