使用Calendar.Month -1查找上个月不能在1月份工作

时间:2014-09-10 05:21:41

标签: android time calendar android-calendar

我必须在我的Maxtime到Mintime之间得到几个月。这个代码在2月之前工作正常。2月之后它永远不会返回Jan。

long max = 1410326172L;//10-Sep-2014
long min = 1388553371L;//1-Jan-2014
    Date maxDate = new Date(max);
    Date minDate = new Date(min);
while (maxDate.getTime() >= minDate.getTime()) {
Calendar cal = getCalendarWithTime(maxDate);            
        long firstDateMillis = DateHelper.getFirstDate(cal);//This is to get the First Date of an particular month.
        long lastDateMillis = DateHelper.getLastDate(cal);//This is to get the Last Date of an particular month
        // substract one month from max date  
        cal.add(Calendar.MONTH, -1); // moving one month in past
        maxDate = cal.getTime();
        System.out.println("------------------"+new SimpleDateFormat("MM").format(maxDate)) 
    }

1 个答案:

答案 0 :(得分:0)

long max = 1410326172L;//10-Sep-2014
long min = 1388553371L;//1-Jan-2014
Date maxDate = new Date(max);
Date minDate = new Date(min);
while (maxDate.getTime() >= minDate.getTime()) {
Calendar cal = getCalendarWithTime(maxDate);            
    long firstDateMillis = DateHelper.getFirstDate(cal);//This is to get the First Date of an particular month.
    long lastDateMillis = DateHelper.getLastDate(cal);//This is to get the Last Date of an particular month

    int test = Integer.parseInt(new SimpleDateFormat("MM").format(maxDate));
        // substract one month from max date
        cal.add(Calendar.MONTH, -1);// moving one month in past
        if (test == 2) {
            if (c == 0) {
                cal.set(Calendar.MONTH, 1);//month of Feb
                maxDate = cal.getTime();
                c++;
            } else {
                cal.set(Calendar.DATE, 30);
                cal.set(Calendar.MONTH, 0);//month of Jan
                maxDate = cal.getTime();
            }
        } else {
            maxDate = cal.getTime();
        }
}

这是一个简单的逻辑,但它解决了我的问题