如何实现Java Date类的compare方法以计算两个日期的天数差?
实现Date类的compare方法计算日期天数差
需求
创建一个名为compare的方法,接收Date类型参数,计算当前对象与输入对象的日期之间的天数差。
现有代码框架
public class Date { int year; int month; int day; void print() { System.out.printf("Date: %d/%d/%d", this.month, this.day, this.year); } void addDays(int n) { int[] month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int i = this.month - 1; int day = this.day + n; while (day > month[i]) { day -= month[i]; if (this.month == 12) { this.year++; this.month = 0; i = -1; } this.month++; i++; } this.day = 0; this.day += day; } int compare(Date d1) { return 0; } }
问题
已完成代码框架,但不知如何实现compare方法。曾尝试基于addDays方法修改,但未能成功,寻求实现建议。
实现建议
直接基于addDays修改不可行,因为addDays会修改当前对象状态,且无法反向计算天数差。正确思路是将两个日期转换为基准日期(如公元1年1月1日)开始的总天数,通过总天数差值得到结果。
步骤1:实现闰年判断辅助方法
原代码未处理闰年,会导致日期计算错误,先补全闰年判断:
private boolean isLeapYear(int year) { if (year % 400 == 0) { return true; } if (year % 100 == 0) { return false; } return year % 4 == 0; }
步骤2:实现计算总天数的辅助方法
编写方法计算当前Date对象从基准日期开始的总天数:
private int getTotalDays() { int total = 0; // 累加当前年份之前所有年份的天数 for (int y = 1; y < year; y++) { total += isLeapYear(y) ? 366 : 365; } // 累加当前年份中之前月份的天数 int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (int m = 0; m < month - 1; m++) { if (m == 1 && isLeapYear(year)) { // 处理闰年2月 total += 29; } else { total += monthDays[m]; } } // 加上当前日期的天数 total += day; return total; }
步骤3:实现compare方法
通过两个日期的总天数差值得到结果,返回值为当前日期总天数 - 参数日期总天数:
int compare(Date d1) { return this.getTotalDays() - d1.getTotalDays(); }
补充:修复原addDays方法的闰年问题
原addDays未处理闰年,同步修改避免计算错误:
void addDays(int n) { int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int i = this.month - 1; int day = this.day + n; while (day > (i == 1 && isLeapYear(this.year) ? 29 : monthDays[i])) { // 减去当前月份的天数 day -= (i == 1 && isLeapYear(this.year) ? 29 : monthDays[i]); if (this.month == 12) { this.year++; this.month = 0; i = -1; } this.month++; i++; } this.day = day; }
内容的提问来源于stack exchange,提问作者msalaz03
相关产品推荐
相关产品推荐

