139
Note this example shows the difference in days, months, and years, but not the
cumulative days or months between two dates. to determine
the total cumulative
days, months, and years between two dates, read on for solutions #2 and #3.
public static void intervals(){
LocalDate anniversary = LocalDate.of(
2015, Month.NOVEMBER, 11);
LocalDate today = LocalDate.now();
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 difference result for today’s date (
2021-12-06).
Number of Days Difference: 25
Number of Months Difference: 0
Number of Years Difference: 6
Solution 2
Use 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 allow you to perform the
necessary calculations.
public static void compareDatesCalendar() {
// 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,0);
Chapter 4 Numbers aNd dates
140
Date date1 = cal2.getTime();
System.out.println(date1);
System.out.println(cal1.getTime());
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) -
TimeUnit.HOURS.toMinutes(hours));
System.out.println(diff);
diff = String.format("%d days", days);
System.out.println(diff);
// Divide the number of days by seven for the weeks
int weeks = days.intValue()/7;
diff = String.format("%d weeks", weeks);
System.out.println(diff);
}
Here is the result for today’s date (
Do'stlaringiz bilan baham: