Friday, July 31, 2009

How do I calculate the difference between two calendar dates in Java?

if you are using Date objects, it's as simple as using the getTime() method... as in





Date x y;


...


long difference = x.getTime() - y.getTime();





otherwise, if you are using Calendar objects, the best way is to use the built-in compareTo() method. It takes another calendar object as argument:





Calendar x y;


...


long difference = x.compareTo(y);





either way will get you the difference in milliseconds.


if you need to do more complex comparisons (like w/ days of the week, etc.) then go to the documentation:





http://java.sun.com/j2se/1.5.0/docs/api/...





-cheers


No comments:

Post a Comment