Friday, March 20, 2009

Find difference between two Date objects in Java

This is an extension of my previous post regarding date-related classes in Java.

Suppose I want to find the difference (in seconds, minutes, days, months, etc) between two Date objects. Currently there is no pre-defined function in any of the earlier mentioned classes to achieve this. But here is a simple code that allows you to do just that.

int difInSeconds = (int)((endDate.getTime() – startDate.getTime()) / 1000)

int difInMinutes =
(int)((endDate.getTime() – startDate.getTime()) / (1000 * 60))

int difInDays =
(int)((endDate.getTime() – startDate.getTime()) / (1000*60*60*24))

Note that in this example, endDate and startDate are Date objects. The reason why this codes work is because when you use the getTime() function of the Date class, you are retrieving the time in milliseconds after January 1, 1970.

No comments:

Post a Comment