当前位置:   article > 正文

通过Calendar计算两个日期之间相差的周次_calendar计算两天日期差

calendar计算两天日期差
public static int getWeekByDate(Date startTime,Date endTime){
    Calendar startCalendar = Calendar.getInstance();
    startCalendar.setTime(startTime);

    Calendar endCalendar = Calendar.getInstance();
    endCalendar.setTime(endTime);

    //总周次
    int sumWeek = 0;
    //判断是否同一年
    if(startCalendar.get(Calendar.YEAR)==startCalendar.get(Calendar.YEAR)){
        //同一年,计算两个周次相减
        sumWeek = endCalendar.get(Calendar.WEEK_OF_YEAR) - startCalendar.get(Calendar.WEEK_OF_YEAR)+1;
    }else{
        //1.起始年剩余的周次
        //2.终止年的周次
        //3.中间经历过的年的总周次

        //1
        sumWeek+=(startCalendar.getWeeksInWeekYear()-startCalendar.get(Calendar.WEEK_OF_YEAR)+1);
        //2
        sumWeek+=endCalendar.get(Calendar.WEEK_OF_YEAR);
        //3
        int year = endCalendar.get(Calendar.YEAR)-startCalendar.get(Calendar.YEAR)-1;
        for (int i = 0; i < year; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR,startCalendar.get(Calendar.YEAR)+i);
            sumWeek+=calendar.getWeeksInWeekYear();
        }
    }
    return sumWeek;
}
  • 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
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/549316
推荐阅读
相关标签
  

闽ICP备14008679号