日期类的加减及java中所以日期类的操作算法大全
2009-09-22 00:00:00 来源:WEB开发网6.计算两个任意时间中间的间隔天数(这个比较常用)
(1)传进Calendar对象
1 public int getIntervalDays(Calendar startday,Calendar endday){
2 if(startday.after(endday)){
3 Calendar cal=startday;
4 startday=endday;
5 endday=cal;
6 }
7 long sl=startday.getTimeInMillis();
8 long el=endday.getTimeInMillis();
9
10 long ei=el-sl;
11 return (int)(ei/(1000*60*60*24));
12 }
13
(2)传进Date对象
1 public int getIntervalDays(Date startday,Date endday){
2 if(startday.after(endday)){
3 Date cal=startday;
4 startday=endday;
5 endday=cal;
6 }
7 long sl=startday.getTime();
8 long el=endday.getTime();
9 long ei=el-sl;
10 return (int)(ei/(1000*60*60*24));
11 }
(3)改进精确计算相隔天数的方法
1 public int getDaysBetween (Calendar d1, Calendar d2) {
2 if (d1.after(d2)) {
3 java.util.Calendar swap = d1;
4 d1 = d2;
5 d2 = swap;
6 }
7 int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
8 int y2 = d2.get(Calendar.YEAR);
9 if (d1.get(Calendar.YEAR) != y2) {
10 d1 = (Calendar) d1.clone();
11 do {
12 days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);//得到当年的实际天数
13 d1.add(Calendar.YEAR, 1);
14 } while (d1.get(Calendar.YEAR) != y2);
15 }
16 return days;
17 }
18
更多精彩
赞助商链接