/** * 获取指定时间前几周以及后几周时间的闭区间时间区域。如果before小于0 before 为0 如果after小于0 * after为0,时间范围的开始时间为目标时间的周一,end为目标时间周的周日 * * @param day 指定时间 * @param before 前几周 * @param after 后几周 * @return */ public static TimeRangeDetail getWeekDays(Date day, int before, int after) { if (day == null) { day = getCurrentDay(); } if (before < 0) { before = 0; } if (after < 0) { after = 0; } Calendar calendar = Calendar.getInstance(); // 获取一周的第一天 向前找整周天 找到begin的范围 calendar.setTime(getMondayOfThisWeek(day)); calendar.add(Calendar.DAY_OF_YEAR, 0 - 7 * before); Date start = calendar.getTime(); // 获取一周的最后一天 向后找整周天 找到end范围 calendar.setTime(getSundayOfThisWeek(day)); calendar.add(Calendar.DAY_OF_YEAR, 7 * after); Date end = calendar.getTime(); return new TimeRangeDetail(TimeRangeDetail.toTime(start), TimeRangeDetail.toTime(end)); }
/** * 获取每个月的第一天 * * @param day * @return */ protected static String getFirstDayOfMonth(Date day) { if (day == null) { day = getCurrentDay(); } String timeStr = TimeRangeDetail.toTime(day); return timeStr.substring(0, 6) + "01"; }
/** * 获取指定时间所在年的最后一天 * * @param day * @return */ protected static String getLastDayOfYear(Date day) { if (day == null) { day = getCurrentDay(); } String timeStr = TimeRangeDetail.toTime(day); return timeStr.substring(0, 4) + "1231"; }
/** * 获取每个月的最后一天 * * @param day * @return */ protected static String getLastDayOfMonth(Date day) { if (day == null) { day = getCurrentDay(); } String timeStr = TimeRangeDetail.toTime(day); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, Integer.parseInt(timeStr.substring(0, 4))); calendar.set(Calendar.MONTH, Integer.parseInt(timeStr.substring(4, 6)) - 1); int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); return timeStr.substring(0, 6) + String.valueOf(maxDay); }
/** * 获取指定时间之前,之后指定的时间的范围 * * @param day 指定时间 * @param before 之前多少天 ,如果表示当前时间,before为0 * @param after 之后多少天,如果表示当前时间,after为0 * @return TimeRange */ public static TimeRangeDetail getDays(Date day, int before, int after) { if (day == null) { day = getCurrentDay(); } if (before < 0) { before = 0; } if (after < 0) { after = 0; } Calendar calendar = Calendar.getInstance(); calendar.setTime(day); // 获取开始时间 calendar.add(Calendar.DAY_OF_YEAR, 0 - before); Date begin = calendar.getTime(); // 获取结束时间 calendar.add(Calendar.DAY_OF_YEAR, 0 + before + after); Date end = calendar.getTime(); return new TimeRangeDetail(TimeRangeDetail.toTime(begin), TimeRangeDetail.toTime(end)); }