Finding days difference in java

后端 未结 5 477
有刺的猬
有刺的猬 2021-01-15 18:53

After consulting a few forums, I ended up using the code below to find the days difference. But, I see a problem with the logic (may be it\'s my over sight?). I see that for

5条回答
  •  遥遥无期
    2021-01-15 19:11

    1000 * 60 * 60 * 24 is wrong way to find day difference. You can use JodaTime but there is a pure java solution.

    Let we have two inialized variables

    Calendar firstDay = ...;
    Calendar secondDay = ...;
    

    and

    firstDay.before(lastDay)
    

    is true.

    Run

    int firstDayNo = firstDay.get(Calendar.DAY_OF_YEAR);
    int secondDayNo = secondDay.get(Calendar.DAY_OF_YEAR);
    int dayDifference, yearMultiplier;
    
    dayDifference = -firstDayNo;
    yearMultiplier = secondDay.get(Calendar.YEAR) - firstDay.get(Calendar.YEAR);
    while (yearMultiplier > 0) {
        dayDifference += firstDay.getActualMaximum(Calendar.DAY_OF_YEAR);
        firstDay.add(Calendar.YEAR, 1);
        yearMultiplier--;
    }
    dayDifference += secondDayNo;
    
    return dayDifference;
    

提交回复
热议问题