Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate the difference between two dates [duplicate]

Tags:

java

Possible Duplicate:
How do I calculate someone's age in Java?

I have two dates eg 19/03/1950 and 18/04/2011. how can i calculate the difference between them to get the person's age? do I have to keep multiplying to get the hours or seconds etc?

like image 612
code511788465541441 Avatar asked Feb 24 '23 22:02

code511788465541441


2 Answers

String date1 = "26/02/2011";
String date2 = "27/02/2011";
String format = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1);
Date dateObj2 = sdf.parse(date2);
long diff = dateObj2.getTime() - dateObj1.getTime();

int diffDays =  (int) (diff / (24* 1000 * 60 * 60));
like image 140
Bala R Avatar answered Feb 27 '23 10:02

Bala R


You use the classes Date and Duration:

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

http://download.oracle.com/javase/1.5.0/docs/api/javax/xml/datatype/Duration.html

You create Date-objects, then use Duration's methods addTo() and subtract()

like image 20
Bernd Elkemann Avatar answered Feb 27 '23 12:02

Bernd Elkemann