/** * 获取两个日期之间天数,周数,月数,年数 * * @param startTime * @param endTime * @param dateType 0-年, 1-月,2-周,3-日 * @return */ public int getBetweenDateNum(String startTime, String endTime, int dateType) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Calendar calendar = Calendar.getInstance(); calendar.setFirstDayOfWeek(Calendar.MONDAY); Calendar calendar1 = Calendar.getInstance(); calendar1.setFirstDayOfWeek(Calendar.MONDAY); try { calendar.setTime(dateFormat.parse(startTime)); calendar1.setTime(dateFormat.parse(endTime)); } catch (ParseException e) { e.printStackTrace(); } int calendarEnum; switch (dateType) { case 1 : calendarEnum = Calendar.MONTH; break; case 2 : calendarEnum = Calendar.WEEK_OF_YEAR; break; case 3 : calendarEnum = Calendar.DAY_OF_YEAR; break; default: calendarEnum = Calendar.YEAR; break; } int startNum = calendar.get(calendarEnum); int endNum = calendar1.get(calendarEnum); // 部分年份的12月最后几天为下年的第一周,所以加此判断,如果获取的周数为1且天数大于100(根据具体情况定义)天,则默认赋值为第52周 int dayNum = 100; if (dateType == 2 && endNum == 1 && calendar1.get(Calendar.DAY_OF_YEAR) > dayNum) { endNum = 52; } int num = startNum - endNum + 1; return num; }
获取两个日期之间天数,周数,月数,年数
最新推荐文章于 2023-01-10 17:31:04 发布