macOsX
macOsX

Reputation: 457

calculating number of days between dates

I'm aware of calculating number of days between two dates.

Java, Calculate the number of days between two dates

But i'm not able to understand how the calculation is made in below piece of code. Particularly the one which is highlighted below.

return (int)( (d2.getTime() - d1.getTime()) / (1000*60*60*24));

Kindly let me know the logic behind this.

Upvotes: 1

Views: 1620

Answers (5)

Habib
Habib

Reputation: 223187

The question you have linked has an answer from Jon Skeet. You should consider that. For your code, the difference between two dates is being returned in Millisecond. To convert into a single day the calculation is:

(1000       *    60     *  60     *    24));
 millisecond  seconds    minutes    hours in day ==> One day

Upvotes: 5

Prateek
Prateek

Reputation: 551

This is pretty straight.

  1. (d2.getTime() - d1.getTime()) gives you diference no. of milli seconds between two dates.

  2. 1000 * 60 * 60 * 24 gives you number of millisecond in a day.

  3. explicit cast to (int) gives you exact number of days.

Nothing more than this.

Upvotes: 0

Lenymm
Lenymm

Reputation: 901

Method getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object as stated in:

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html

And I believe I don't even have to describe the rest as this is the only thing that might be unclear to you ;)

Upvotes: 0

Shiva Komuravelly
Shiva Komuravelly

Reputation: 3280

Dude getTime() method gives you time in milliseconds. So diffrence would be millis only then you try to covert it into seconds by dividing it by 1000 then to minutes by dividing it by 60 then to hours then to days (1 day is 24 hrs).

I hope you get it.

Upvotes: 0

Alex
Alex

Reputation: 25613

The time is represented as millisecond, so you have 24 * 60 * 60 * 1000 because

24 * there are 24 hours in a day
60 * there are 60 minutes in an hour
60 * there are 60 seconds in a minute
1000 * there are 1000 milliseconds in a second

Upvotes: 0

Related Questions