Java 17 Recipes


-15. Finding the Interval Between Dates and Times


Download 3.2 Mb.
Pdf ko'rish
bet84/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   80   81   82   83   84   85   86   87   ...   245
Bog'liq
Java 17 Recipes

4-15. Finding the Interval Between Dates and Times
 Problem
You need to determine how many hours, days, weeks, months, or years have elapsed 
between two dates or times.
 Solution 1
Utilize the Date-Time API to determine the difference between two dates. Specifically
use the Period class to determine the period of time, in days, between two dates. The 
following example demonstrates how to obtain the interval of days, months, and years 
between two dates.
Chapter 4 Numbers aNd dates


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 (

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   80   81   82   83   84   85   86   87   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling