java算法编程题:计算两个日期之间相隔的天数

/**
 * 计算两个日期之间相隔的天数
 * 
 * @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;
	}
}

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值