我是Java新手
如何获得两(2)个jdatechooser之间的总月数?我已经搜索过有关此内容的信息,但日期已设置为代码。就我而言,我想通过JDateChooser放置日期。
我可以通过此代码执行此操作,但是如果更改年份,则不使用JodaTime
就无法计算要执行的月份总数。
这是我的代码
public void month(){
int TotalMonth;
Calendar toDate;
Calendar fromDate;
int increment;
Date dt1 = date1.getDate(); //datechooser 1
Date dt2 = date2.getDate(); //datechooser 2
fromDate = Calendar.getInstance();
toDate = Calendar.getInstance();
if(dt1.after(dt2))
{
fromDate.setTime(dt2);
toDate.setTime(dt1);
}
else
{
fromDate.setTime(dt1);
toDate.setTime(dt2);
}
increment = 0;
TotalMonth = toDate.get(Calendar.MONTH) - (fromDate.get(Calendar.MONTH + increment));
jLabel2.setText(Integer.toString(age));
}
最佳答案
JodaTime
比较简单,但是...
您需要从开始时间到结束循环,在每个循环中增加MONTH
字段,同时将日期保留在结束时间之前...
例如...
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal1 = Calendar.getInstance();
cal1.setTime(sdf.parse("08/03/1972"));
Calendar cal2 = Calendar.getInstance();
cal2.setTime(sdf.parse("08/03/2014"));
// Yes, you can use cal1, but I you might want
// to preserve it for other reasons...
Calendar cal3 = Calendar.getInstance();
cal3.setTime(cal1.getTime());
int months = 0;
while (cal3.before(cal2)) {
cal3.add(Calendar.MONTH, 1);
months++;
}
System.out.println("Months = " + months);
} catch (ParseException exp) {
exp.printStackTrace();
}
打印出
Months = 505
。如果将
cal2
更改为08/04/1972
,它将打印Months = 1