| Author |
Number of days between dates
|
Varun Gokulnath
Greenhorn
Joined: May 22, 2011
Posts: 7
|
|
Hi,
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.
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
something like:
|
 |
Alexey Dubinin
Greenhorn
Joined: Mar 23, 2010
Posts: 2
|
|
|
This is bad solution because daylight saving changes can lead to error in calculations. You can try Joda time library.
|
 |
Varun Gokulnath
Greenhorn
Joined: May 22, 2011
Posts: 7
|
|
|
Thanks Seetharaman but I don't think the "-" operator can be applied to two Date object operands.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19214
|
|
Except that doesn't work well with daylight savings time.
In pseudo code, assuming first <= second:
A bit more advanced:
This latter can be explained with two examples:
1) February 1st 2010 and March 1st 2011.
count = (31 + 28 + 1) - (31 + 1) = 28.
2010 < 2011 so count += 365 => count = 393.
2) March 1st 2010 and February 1st 2011.
count = (31 + 1) - (31 + 28 + 1) = -28 (yes, negative; that'll be corrected).
2010 < 2011 so count += 365 => count = 337.
The methods to use from Calendar are add for adding a day / year, and getActualMaximum to get the numbers in the year. getActualMaximum will return 365 or 366, getMaximum will always return 366.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
Alexey Dubinin wrote:This is bad solution because daylight saving changes can lead to error in calculations.
thanks for remembering the daylight saving problem .
Varun Gokulnath wrote:Thanks Seetharaman but I don't think the "-" operator can be applied to two Date object operands.
getTime returns long
|
 |
Varun Gokulnath
Greenhorn
Joined: May 22, 2011
Posts: 7
|
|
Thanks Alexey, Seetharaman and Rob.
@Seetharaman : I am able to get a good estimate by using your method
@Rob:Can you tell me if I am using your method correctly because I am not arriving at the right answer.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19214
|
|
Varun Gokulnath wrote:
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.
|
 |
 |
|
|
subject: Number of days between dates
|
|
|