How to get difference between dates in Java

Member

zora.stokes

by zora.stokes , in category: Java , a month ago

How to get difference between dates in Java 😁

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public static long getDifference(Date date1, Date date2, int unit) {
	if (date1 == null || date2 == null) {
		throw new IllegalArgumentException("Date cannot be null!");
	}

	if (date1.after(date2)) {
		Date swap = date1;
		date1 = date2;
		date2 = swap;
	}
		
	long result = 0;
	
	long diff = date2.getTime() - date1.getTime() + (60 * 60 * 1000L);
		
	switch (unit) {
	case Calendar.YEAR:
		result = diff / (60 * 60 * 24 * 365 * 1000L);
		break;
	case Calendar.MONTH:
		result = diff / (60 * 60 * 24 * 30 * 1000L);
		break;
	case Calendar.DAY_OF_YEAR:
		result = diff / (60 * 60 * 24 * 1000L);
		break;
	default:
		throw new UnsupportedOperationException("Impossible to get time difference in coerced unit.");
	}
		
	return result;
}


Facebook Twitter LinkedIn Telegram Whatsapp Pocket

no answers