Android编程实现根据不同日期计算天数差的方法

时间:2022-04-10 06:19:04

本文实例讲述了Android编程实现根据不同日期计算天数差的方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Calendar cal1 = getCalendarFromDate(mStartDate);
long startTime = cal1.getTimeInMillis();
Calendar cal2 = getCalendarFromDate(mEndDate);
long endTime = cal2.getTimeInMillis();
int numberOfDays = (int)(endTime - startTime)/(24 * 60 * 60 * 1000);
/**
* @param date format is 2012-9-18
* @return Calendar value is after set date's value
*/
private Calendar getCalendarFromDate(final String date) {
    int year = 0;
    int month = 0;
    int day = 0;
    try {
      String[] array = date.split("-");
      int[] arrayInt = new int[array.length];
      for (int i = 0; i < array.length; i++) {
        arrayInt[i] = Integer.parseInt(array[i]);
        if(i == 0) {
          year = arrayInt[0];
        } else if(i == 1){
          month = arrayInt[1];
        } else if(i == 2){
          day = arrayInt[2];
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    Calendar cal = Calendar.getInstance();
    if(year > 0 && month >= 0 && day >= 0) {
      cal.set(year, month, day);
    }
    return cal;
}

PS:month 取值范围为0-11

希望本文所述对大家Android程序设计有所帮助。