如何使用JDateChooser获取/计算总月数

时间:2014-08-27 05:44:21

标签: java swing jdatechooser

我是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));

}

1 个答案:

答案 0 :(得分:2)

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