1. 程式人生 > >計算兩個Calendar類引數相差的天數

計算兩個Calendar類引數相差的天數

初學Android,遇到這個問題還不知道怎麼辦,Android沒有提供函式來計算,而且自己資料庫用的是MySQL,也是自己不熟悉的資料庫,就沒有過多的想用SQL來寫。

在網上找了幾個,感覺有些複雜,想了想有一點思路,寫出來可以實現

思路:

  1. 首先判斷是否日期一前一後
  2. 邊計數邊增加比較早的日期
  3. 等到兩個日期一樣時,停止操作,返回計數
/**
 * Created by Harry on 2015/4/27.
 * This class is used for compute days between two different dates
 */
public class DateCompute {

    private static String TAG = DateCompute.class.getName();

    private static Calendar startDate;
    private static Calendar endDate;
    private static int dayCount;

    public DateCompute(Calendar p_startDate, Calendar p_endDate) {
        startDate = p_startDate;
        endDate = p_endDate;
        dayCount = 0;
    }

    /**
     * Since both are Calendar, there is no need to add one more month each.
     * @return
     */
    public int computeCalendar(){
        /*if startDate is before endDate, loop continues*/
        while(startDate.before(endDate)){
            startDate.add(Calendar.DAY_OF_MONTH, 1);
            dayCount++;
        }
        Log.v(TAG, "$$$$$$ days between two dates are : " + dayCount);
        return dayCount;
    }


}

注意:

  1. Calendar類中,MONTH是比真實日期小1的,所以傳遞引數的時候注意變換
  2. 如果遇到String型別的,要先轉換成Calendar,下面的程式碼可以實現
這裡我自己定義的字串日期格式為:yyyy-MM-dd

方法也就是取substring,然後分別賦值給Calendar物件(資料全是資料庫裡提取的資料,資料庫函式就沒有貼上了)

    private static void calendarMinus(){
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();

        String sql = "select startDate, endDate from habit where userID = 2 and habitID = 2;";
        Cursor cursor = Database.getDatabase().getWritableDatabase().rawQuery(sql, null);
        String start, end;
        cursor.moveToFirst();

        start = cursor.getString(cursor.getColumnIndex("startDate"));
        end = cursor.getString(cursor.getColumnIndex("endDate"));
        /*yyyy-MM-dd*/
        calendar1.set(Calendar.YEAR, Integer.parseInt(start.substring(0,4)));
        calendar1.set(Calendar.MONTH, Integer.parseInt(start.substring(5,7)));
        calendar1.set(Calendar.DAY_OF_MONTH, Integer.parseInt(start.substring(8,10)));

        calendar2.set(Calendar.YEAR, Integer.parseInt(end.substring(0,4)));
        calendar2.set(Calendar.MONTH, Integer.parseInt(end.substring(5,7)));
        calendar2.set(Calendar.DAY_OF_MONTH, Integer.parseInt(end.substring(8,10)));

        DateCompute compute = new DateCompute(calendar1, calendar2);
        compute.computeCalendar();
    }