私の方法は、年の違いだけを知りたいので、私の問題は私がこれを行うことで非常に効率が悪いことです。私は、このメソッドを書くのにははるかに単純で審美的に喜ばしい方法があると感じています。2つの日付の違いを見つける方法
編集:私自身の方法を書く必要があります。私はまた、自分のやり方から脱して、初級プログラマーの範囲内にある先進的なものを使うことを好まない。
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;
}
[2つのJava日付インスタンス間の差異を計算する]の可能な複製(http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances) –
あなた自身でこの方法を書いてください。組み込みのライブラリ呼び出しを使用する方がはるかに良いでしょう。 –
これは 'MyDate'オブジェクトです。彼は自分自身で書きました。 –