Meine Methode funktioniert, da ich nur den Unterschied in Jahren wissen möchte, mein Problem ist, dass ich so ineffizient dabei bin. Ich habe das Gefühl, dass es viel einfacher und ästhetisch angenehmer ist, die Methode zu schreiben.Eine Methode, um den Unterschied zwischen zwei Daten zu finden
Edit: Ich muss meine eigene Methode schreiben. Ich ziehe es auch vor, nicht aus dem Weg zu gehen und fortgeschrittene Dinge zu verwenden, etwas im Bereich eines Programmierers für das erste Jahr.
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;
}
werde ich die MyDate
Klasse unten Kontext hinzufügen:
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;
}
Mögliches Duplikat von [Berechnung der Differenz zwischen zwei Java-Datumsinstanzen] (http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances) –
Müssen Sie tun schreibe diese Methode selbst? Es wäre viel besser, einen integrierten Bibliotheksaufruf zu verwenden. –
Es ist ein 'MyDate' Objekt. Er hat es selbst geschrieben. Ich denke, –