I need to calculate the number of days passed between 2 dates using java.util.Date, java.util.Calendar and java.text.SimpleDateFormat. I'm breaking my brain, how could I accomplish that?
Asked
Active
Viewed 138 times
-4
-
101. Is this homework? 2. What have you tried? – Tomasz Nurkiewicz May 08 '12 at 21:02
-
1`how could I accomplish that` - hardly – Dmitry Zaytsev May 08 '12 at 21:03
-
1No guys I've done half of the task and I doubt that it would be effective to subtract current date from the date given using Calendar and than iterate until the year == 0 adding to the sum 365/366 days... – OneMoreVladimir May 08 '12 at 21:07
-
No indeed would anyone help after the previous two gentlemen wrapped the problem into the 'homework' paper? – OneMoreVladimir May 08 '12 at 21:12
-
2Can you use JodaTime's Days.daysBetween? – fgb May 08 '12 at 21:15
-
I've used it and the solution was quite elegant, but I need to use only standard API. – OneMoreVladimir May 08 '12 at 21:16
-
java.util.Date is in UTS so a simple math like this will give you what you want int daysBetween = (endDate.getTime() - startDate.getTime())/totalMillisecondsInADay – Aravind Yarram May 08 '12 at 21:22
-
1Check this question : http://stackoverflow.com/questions/3299972/difference-in-days-between-two-dates-in-java – StepTNT May 08 '12 at 21:23
1 Answers
1
It seems like an interview question, similar was asked to me in an interview 2 months back.
Well, here is another hint: You have two dates. Java gives you time in millis for each date. Say t1 and t2.
Without loss of generality we can assume t1>t2. now t = t1-t2
divide t by 86400 * 1000 ( number of milliseconds in a day) and that is your answer :)

dharam
- 7,882
- 15
- 65
- 93