Java Reference
In-Depth Information
Period period = Period.between(anniversary, today);
System.out.println("Number of Days Difference: "
+ period.getDays());
System.out.println("Number of Months Difference: "
+ period.getMonths());
System.out.println("Number of Years Difference: "
+ period.getYears());
Here is the result:
Number of Days Difference: 16
Number of Months Difference: 1
Number of Years Difference: 13
Solution #2
Use the java.util.concurrent.TimeUnit enum to perform calculations
between given dates. Using this enum , you can obtain the integer values for days,
hours, microseconds, milliseconds, minutes, nanoseconds, and seconds. Doing so will
allow you to perform the necessary calculations.
// Obtain two instances of the Calendar class
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
// Set the date to 01/01/2010:12:00
cal2.set(2010,0,1,12,0);
Date date1 = cal2.getTime();
System.out.println(date1);
long mill = Math.abs(cal1.getTimeInMillis()
- date1.getTime());
// Convert to hours
long hours = TimeUnit.MILLISECONDS.toHours(mill);
// Convert to days
Long days = TimeUnit.HOURS.toDays(hours);
String diff = String.format("%d hour(s) %d min(s)", hours,
TimeUnit.MILLISECONDS.toMinutes(mill)
Search WWH ::




Custom Search