我的方法是有效的,因为我只想知道几年之间的差异,我的问题是我这样做效率低下。我有一种感觉,写出这种方法有一种更加简单和美观的方式。找到两个日期之间的差异的方法
编辑:我必须写我自己的方法。我也更喜欢不要走出自己的路,并使用先进的东西,在一年级程序员的范围内。
public int differenceInYears(MyDate comparedDate) {
int difference = 0;
if (this.year > comparedDate.year) {
if (this.month > comparedDate.month) {
difference = this.year - comparedDate.year;
}
else if (this.month == comparedDate.month) {
if (this.day >= comparedDate.day) {
difference = this.year - comparedDate.year;
}
else {
difference = this.year - comparedDate.year - 1;
}
}
else {
difference = this.year - comparedDate.year - 1;
}
}
if (comparedDate.year > this.year) {
if (comparedDate.month > this.month) {
difference = comparedDate.year - this.year;
}
else if (comparedDate.month == this.month) {
if (comparedDate.day >= this.day) {
difference = comparedDate.year - this.year;
}
else {
difference = comparedDate.year - this.year - 1;
}
}
else {
difference = comparedDate.year - this.year - 1;
}
}
return difference;
}
我将添加MyDate
类下面的背景:
public class MyDate {
private int day;
private int month;
private int year;
public MyDate(int day, int montd, int year) {
this.day = day;
this.month = montd;
this.year = year;
}
public String toString() {
return this.day + "." + this.month + "." + this.year;
}
public boolean earlier(MyDate compared) {
if (this.year < compared.year) {
return true;
}
if (this.year == compared.year && this.month < compared.month) {
return true;
}
if (this.year == compared.year && this.month == compared.month
&& this.day < compared.day) {
return true;
}
return false;
}
[计算两个Java日期实例之间的差异]的可能重复(http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances) –
您需要自己写这个方法?使用内置的库调用会更好。 –
这是一个MyDate对象。他自己写了我认为 –