我有一个开始日期和结束日期。两个日期之间的持续时间应采用年、月和日的形式。我是java新手。当我运行以下方法时,我得到的结果是 0 年 12 个月 1 天。请提出一个替代方案,以获得年、月和日的准确差异。
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Duration {
private String getAssignmentDuration(java.util.Date oldDate, java.util.Date newDate) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
if (oldDate.compareTo(newDate) > 0) {
c1.setTime(newDate);
c2.setTime(oldDate);
} else {
System.out.println("invalid");
return "Invalid selection";
}
int year = 0;
int month = 0;
int days = 0;
boolean doneMonth = false;
boolean doneYears = false;
while (c1.before(c2)) {
//log.debug("Still in Loop");
if (!doneYears) {
c1.add(Calendar.YEAR, 1);
year++;
}
if (c1.after(c2) || doneYears) {
if (!doneYears) {
doneYears = true;
year--;
c1.add(Calendar.YEAR, -1);
}
if (!doneMonth) {
c1.add(Calendar.MONTH, 1);
month++;
}
if (c1.after(c2) || doneMonth) {
if (!doneMonth) {
doneMonth = true;
month--;
c1.add(Calendar.MONTH, -1);
}
c1.add(Calendar.DATE, 1);
days++;
if (c1.after(c2)) {
days--;
}
// this will not be executed
if (days == 31 || month==12) {
break;
}
}
}
}
System.out.println(year + " years, " + month + " months, " + days + " days");
return year + " years, " + month + " months, " + days + " days";
}
public static void main(String[] args) {
Duration d1= new Duration();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
java.util.Date oldDate = null;
try {
oldDate = sdf.parse("2012/08/29");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
java.util.Date newDate = null;
try {
newDate = sdf.parse("2013/08/31");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
d1.getAssignmentDuration(oldDate, newDate);
}
}