วันพุธที่ 1 กรกฎาคม พ.ศ. 2552

เขียนเล่น:DateDiff

import java.util.*;

public class DateDiff {

private static int getDayInYear(int year) {
int return_diy = 0;
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
return_diy = 366;
} else {
return_diy = 365;
}
return return_diy;
}

private static long getDaysBetweenYear(int startYear, int endYear) {
long return_dbm = 0;
for (int c_year = startYear; c_year <= endYear; c_year++) {
return_dbm = return_dbm + getDayInYear(c_year);
}
return return_dbm;
}

private static long getFullDayDiff(Calendar startDate, Calendar endDate) {
long return_fdd = 0;
int s1 = 0;
int s2 = 0;
long s3 = 0;
boolean sYear = false;

sYear = (startDate.get(Calendar.YEAR) == endDate.get(Calendar.YEAR));

if (sYear) {
s1 = startDate.get(Calendar.DAY_OF_YEAR);
s2 = endDate.get(Calendar.DAY_OF_YEAR);
return_fdd = s2 - s1;
} else {
s1 = getDayInYear(startDate.get(Calendar.YEAR));
s1 = s1 - startDate.get(Calendar.DAY_OF_YEAR);

s2 = endDate.get(Calendar.DAY_OF_YEAR);

s3 = getDaysBetweenYear((startDate.get(Calendar.YEAR) + 1),
(endDate.get(Calendar.YEAR) - 1));

return_fdd = s1 + s2 + s3;
}
System.out.println("-----------------------------------");
return return_fdd;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

cal1.set(2011, Calendar.JANUARY, 10);
cal2.set(2013, Calendar.MARCH, 10);

System.out.println("cal1:" + cal1.getTime().toString());
System.out.println("cal2:" + cal2.getTime().toString());
System.out.println("-----------------------------------");
System.out.println("getFullDayDiff:" + getFullDayDiff(cal1, cal2));

}
}

ไม่มีความคิดเห็น: