如何从特定日期获取总月数?

How to get total number of months from a specific Date?

我是新手 Android.I 有一个要求,我有一个字段可以输入 person.On 成功选择的出生日期 我想 return 的总月数当前 date.For 示例的 DOB,如果我输入 DOB 作为 19/10/2012 我想要 return 36(个月)。我搜索了这个,但没有找到适合我的东西 requirement.Here 是我当前的代码,其中 return 成功的数据,

private void showDate(int year, int month, int day) {

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(0);
    cal.set(year, month, day);
    Date date = cal.getTime();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    if(System.currentTimeMillis() > date.getTime()) {
        edtDate.setText(sdf.format(date));
        LocalDate date1 = new LocalDate(date);
        LocalDate date2 = new LocalDate(new java.util.Date());
        PeriodType monthDay = PeriodType.yearMonthDayTime();
        Period difference = new Period(date1, date2, monthDay);
        int months = difference.getMonths();
        months=months + 1;
        System.out.println("16102015:Nunber of Months"+months);
    }else{
        Toast.makeText(mActivity,getResources().getString(R.string.date_validationmsg),Toast.LENGTH_LONG).show();
    }


}
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);

int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);

使用 JodaTime,真的很简单:

首先,我建议使用 LocalDate instead of DateTime 进行计算。理想情况下,根本不要使用 java.util.Date,并将您的输入作为 LocalDate 开始(例如,通过直接将文本解析为该文本,或者您的数据来自何处。)将两个日期中的日期设置为 1 ,然后取月差:

private static int monthsBetweenDates(LocalDate start, LocalDate end) {
    start = start.withDayOfMonth(1);
    end = end.withDayOfMonth(1);
    return Months.monthsBetween(start, end).getMonths();
}

更新 1

参见 this link OP 接受了相同的答案,因为 Months.monthsBetween() 方法不适合他

更新 2

LocalDate userEnteredDate = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date));    
LocaleDate currentDate =  LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

int months = monthsBetweenDates(userEnteredDate, currentDate)

使用此代码计算两个日期之间的月份

public static int monthsBetweenUsingJoda(Date d1, Date d2) {
    return Months.monthsBetween(new LocalDate(d1.getTime()), new LocalDate(d2.getTime())).getMonths();
}

使用 Joda-time 库 here,我能够得到想要的结果。 试试下面的代码,它会以月为单位给出所需的差异。

    DateTime date1 = new DateTime().withDate(2012, 10, 19);
    DateTime today = new DateTime().withDate(2015, 10, 19);
    // calculate month difference
    int diffMonths = Months.monthsBetween(date1.withDayOfMonth(1), today.withDayOfMonth(1)).getMonths();