数组中日期之间的差异

时间:2014-04-18 09:26:41

标签: java

我必须对Date []进行排序,并计算条目之间的最大跨度。这些值从字符串值解析为Date(从数据库传递) 示例日期数组如下所示:

Date[] myDateArray = {01/01/2014,03/01/2014,04/01/2014,07/01/2014,19/01/2014};

这是我方法的一小部分。

temp = i_value = j_value = max = maxdiff = diff = 0;

for (int i = 0; i < dateValues.length; i++) {
    for (int j = i + 1; j < dateValues.length; j++) {
        cal.setTime(dateValues[i]);
        i_value = (cal.get(Calendar.YEAR) * 365) + cal.get(Calendar.DAY_OF_YEAR);
        cal.setTime(dateValues[j]);
        j_value = (cal.get(Calendar.YEAR) * 365) + cal.get(Calendar.DAY_OF_YEAR);
        max = Math.abs(i_value - j_value);
    }
    diff = Math.abs(max - max2);
    if (maxdiff < diff) {
        maxdiff = diff;
    }
    temp = maxdiff;
}
return temp;

2 个答案:

答案 0 :(得分:1)

以下代码将为您提供两个日期之间的日期。

  public  int getDaysBetween(Date date1, Date date2) {

    Calendar d1 = Calendar.getInstance();
    Calendar d2 = Calendar.getInstance();
    d1.setTime(date1);
    d2.setTime(date2);

    int days = d2.get(Calendar.DAY_OF_YEAR)
            - d1.get(Calendar.DAY_OF_YEAR);
    int y2 = d2.get(Calendar.YEAR);
    try {
        if (d1.get(Calendar.YEAR) < y2) {
            d1 = (Calendar) d1.clone();
            do {
                days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);
                d1.add(Calendar.YEAR, 1);
            } while (d1.get(Calendar.YEAR) != y2);
        } else if (d1.getCalendar.YEAR) > y2) {
            d1 = (Calendar) d1.clone();
            do {
                days -= d1.getActualMaximum(Calendar.DAY_OF_YEAR);
                d1.add(Calendar.YEAR, -1);
            } while (d1.get(Calendar.YEAR) != y2);
            if ((y2 % 4) == 0) {
                days -= 1;
            }
        }

    } catch (Exception exp) {
        exp.printStackTrace();

    }

    return days+1;
}

希望这会对你有所帮助:)。

答案 1 :(得分:0)

此代码不使用日历。

/**
 * Ascertain the largest span between dates of a sorted array in days.
 * @param sortedDateArray Sorted array of java.util.Dates without nulls
 * @return largest span between two batched dates in sortedDateArray in days
 */
public static int largestSpan(Date[] sortedDateArray) {
    int maxDiffDays = 0;
    for (int i = 0, j = 1; i < sortedDateArray.length && j < sortedDateArray.length; i = j++) {
        Date b = sortedDateArray[i + 1];
        Date a = sortedDateArray[i];
        long diff = b.getTime() - a.getTime(); // calculates the difference between to batched dates (a and b) in ms
        int diffDays = (int) (diff / (1000 * 60 * 60 * 24)); // converts the difference from ms to days

        System.out.println(diffDays + " days between " + a.toString()
                + " and " + b.toString()); // prints out the difference in days (just for debugging)

        if (diffDays > maxDiffDays)
            maxDiffDays = diffDays; // sets the difference as new maximum difference if it is larger than the previous value
    }
    return maxDiffDays; // returns the largest difference in days
}