计算两个日期之间相差的年份,月份,天数

计算两个日期之间相差的年份,月份,天数

使用Calendar类的相关方法进行计算。

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
32
33
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Test {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String str1 = "2005-08-09 10:25:03";
String str2 = "2016-01-05 19:06:29";

try {
Date dateBefore = sdf.parse(str1);
Date dateAfter = sdf.parse(str2);

Calendar calendarBefore = Calendar.getInstance();
Calendar calendarAfter = Calendar.getInstance();

calendarBefore.setTime(dateBefore);
calendarAfter.setTime(dateAfter);

int betweenDays = calendarAfter.get(Calendar.DATE) - calendarBefore.get(Calendar.DATE);
int betweenMonths = calendarAfter.get(Calendar.MONTH) - calendarBefore.get(Calendar.MONTH);
int betweenYears = calendarAfter.get(Calendar.YEAR) - calendarBefore.get(Calendar.YEAR);

System.out.println("betweenDays = " + betweenDays);
System.out.println("betweenMonths = " + betweenMonths);
System.out.println("betweenYears = " + betweenYears);
} catch (ParseException e) {
e.printStackTrace();
}
}

The output :

1
2
3
betweenDays = -4
betweenMonths = -7
betweenYears = 11