EN
Java - calculate difference between two Dates in days
8 points
In java we can calculate difference between two Dates with TimeUnit class.
xxxxxxxxxx
1
import java.time.LocalDateTime;
2
import java.time.ZoneOffset;
3
import java.util.Date;
4
import java.util.concurrent.TimeUnit;
5
6
public class CalculateDifferenceBetweenDays {
7
8
public static void main(String[] args) {
9
10
LocalDateTime of1 = LocalDateTime.of(2019, 10, 3, 16, 20, 0, 0);
11
LocalDateTime of2 = LocalDateTime.of(2019, 10, 12, 16, 20, 0, 0);
12
13
Date from = Date.from(of1.toInstant(ZoneOffset.UTC));
14
Date now = Date.from(of2.toInstant(ZoneOffset.UTC));
15
16
long differenceDays = calculateDifferenceBetweenTwoDatesInDays(from, now);
17
18
System.out.println("Diff in days: ");
19
System.out.println(differenceDays); // 9
20
}
21
22
public static long calculateDifferenceBetweenTwoDatesInDays(Date from, Date now) {
23
long millisecondsDiff = now.getTime() - from.getTime();
24
return TimeUnit.DAYS.convert(millisecondsDiff, TimeUnit.MILLISECONDS);
25
}
26
}
Output:
xxxxxxxxxx
1
Diff in days:
2
9