/**
* 计算两个日期之间相隔的天数
*
* @author zql
*
*/
public class Test {
public static void main(String[] args) {
Test t = new Test();
int r = t.getDaySub(2020, 1, 1, 2020, 2, 5);
System.out.println(r);
}
/**
* @param startYear 开始年
* @param startMonth 开始月
* @param startDay 开始日
* @param endYear 结束年
* @param endMonth 结束月
* @param endDay 结束日
* @return 相隔的天数
*/
public int getDaySub(int startYear, int startMonth, int startDay, int endYear, int endMonth, int endDay) {
// 总天数
int totalDay = 0;
// 年相等
if (startYear == endYear) {
// 月相等
if (startMonth == endMonth) {
totalDay = endDay - startDay;
// 月不等
} else {
for (int i = 0; i <= (endMonth - startMonth); i++) {
// 第一个月可能不是从1号开始,所以另算
if (i == 0) {
totalDay += (getThisYearMonthDays(startYear, startMonth) - startDay);
// 最后一个月可能不是从月底结束结束,所以另算
} else if (i == (endMonth - startMonth)) {
totalDay += endDay;
} else {
totalDay += getThisYearMonthDays(startYear, startMonth + i);
}
}
}
// 年不相等
} else {
for (int i = 0; i <= (endYear - startYear); i++) {
// 第一年
if (i == 0) {
for (int j = startMonth; j < 13; j++) {
int month = j;
int days = getThisYearMonthDays(startYear, month);
// 第一年的开始月份
if (j == startMonth) {
days = getThisYearMonthDays(startYear, month) - startDay;
}
totalDay += days;
}
// 最后一年
} else if (i == (endYear - startYear)) {
for (int j = 1; j <= endMonth; j++) {
int month = j;
int eDay = getThisYearMonthDays(endYear, month);
// 结束日期的最后一天小于最后一月的天数
if (j == endMonth && endDay < eDay) {
eDay = endDay;
}
totalDay += eDay;
}
// 中间年
} else {
int year = startYear + i;
if (isLeapYear(year)) {
totalDay += 366;
} else {
totalDay += 365;
}
}
}
}
return totalDay;
}
/**
* 获取某年某月的天数
*
* @param year 年份
* @param month 月份
* @return int类型,天数
*/
public int getThisYearMonthDays(int year, int month) {
if (month == 2) {
return isLeapYear(year) ? 29 : 28;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else {
return 31;
}
}
/**
* 判断是否是闰年,是返回true,不是返回false
*
* @param year 年份
* @return boolean 类型
*/
public boolean isLeapYear(int year) {
return (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0) ? true : false;
}
}
java算法编程题:计算两个日期之间相隔的天数
最新推荐文章于 2024-08-01 21:00:46 发布