How to calculate the difference between two dates

Possible duplicate:
How to calculate a person’s age in Java?

I have two dates, for example, 19/03/1950 and 18/04/2011. How can I calculate the difference between them to get a person’s age? Do I need to keep multiplying to get hours or seconds, etc.?

+4
source share
4 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)); 
+5
source

The following code will give you the difference between two dates:

 import java.util.Date; import java.util.GregorianCalendar; public class DateDiff { public static void main(String[] av) { /** The date at the end of the last century */ Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime(); /** Today date */ Date today = new Date(); // Get msec from each, and subtract. long diff = today.getTime() - d1.getTime(); System.out.println("The 21st century (up to " + today + ") is " + (diff / (1000 * 60 * 60 * 24)) + " days old."); } } 
+1
source

Why not use jodatime ? It is much easier to calculate date and time in java.

You can get the year and use the yearsBetween () method

+1
source

You are using Date and Duration classes:

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 the Duration addTo () and subtract () methods

0
source

Source: https://habr.com/ru/post/1342290/


All Articles