java在很多场合下会根据当前时间计算本季度的开始时间结束时间、当前月份的开始时间结束时间、当前周的开始时间以及结束时间。我这里整理下一个时间加工类,作为工具类记录下。
一、获取计算相关时间的方法如下:(如果有错误请指出,感谢!)
public class TimeUtils {
/**
* 初始化时间盒子
* @return timeBox
*/
public static TimeBox initTimeBox() throws ParseException {
TimeBox timeBox = new TimeBox();
Date currentDate = new Date();
timeBox.setCurrentDate(currentDate);
Date lastDate = getLastDate(currentDate);
timeBox.setLastDate(lastDate);
timeBox.setThisWeekStartDate(getCurrentWeekDateBegin(lastDate));
timeBox.setThisWeekEndDate(getCurrentWeekDateEnd(lastDate));
timeBox.setThisMonthStartDate(getCurrentMonthDateBegin(lastDate));
timeBox.setThisMonthEndDate(getCurrentMonthDateEnd(lastDate));
timeBox.setLastWeekStartDate(getLastWeekDateBegin(lastDate));
timeBox.setLastWeekEndDate(getLastWeekDateEnd(lastDate));
timeBox.setLastMonthStartDate(getLastMonthDateBegin(lastDate));
timeBox.setLastMonthEndDate(getLastMonthDateEnd(lastDate));
timeBox.setThisQuarterStartDate(getCurrentQuarterDateBegin(lastDate));
timeBox.setThisQuarterEndDate(getCurrentQuarterDateEnd(lastDate));
timeBox.setThisSundayDate(getCurrentWeekNumberDay(lastDate,0));
timeBox.setLastSundayDate(getLastWeekDate(getCurrentWeekNumberDay(lastDate,0)));
timeBox.setThisMondayDate(getCurrentWeekNumberDay(lastDate,1));
timeBox.setLastMondayDate(getLastWeekDate(getCurrentWeekNumberDay(lastDate,1)));
timeBox.setThisTuesdayDate(getCurrentWeekNumberDay(lastDate,2));
timeBox.setLastTuesdayDate(getLastWeekDate(getCurrentWeekNumberDay(lastDate,2)));
timeBox.setThisWednesdayDate(getCurrentWeekNumberDay(lastDate,3));
timeBox.setLastWednesdayDate(getLastWeekDate(getCurrentWeekNumberDay(lastDate,3)));
timeBox.setThisThursdayDate(getCurrentWeekNumberDay(lastDate,4));
timeBox.setLastThursdayDate(getLastWeekDate(getCurrentWeekNumberDay(lastDate,4)));
timeBox.setThisFridayDate(getCurrentWeekNumberDay(lastDate,5));
timeBox.setLastFridayDate(getLastWeekDate(getCurrentWeekNumberDay(lastDate,5)));
timeBox.setThisSaturdayDate(getCurrentWeekNumberDay(lastDate,6));
timeBox.setLastSaturdayDate(getLastWeekDate(getCurrentWeekNumberDay(lastDate,6)));
//确认当前周几,获取本周的所有日期
timeBox.setStartDate(getEarliestDate(getLastMonthDateBegin(lastDate),getCurrentQuarterDateBegin(lastDate)));
timeBox.setEndDate(getCurrentQuarterDateEnd(lastDate));
return timeBox;
}
public static Date getEarliestDate(Date lastMonthStartDate, Date thisQuarterDateBegin) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = lastMonthStartDate;
if (getDayDiffer( simpleDateFormat.parse(simpleDateFormat.format(thisQuarterDateBegin)),simpleDateFormat.parse(simpleDateFormat.format(lastMonthStartDate))) > 0){
date = thisQuarterDateBegin;
}
return date;
}
/**
* 获取昨天日期
* @return date
*/
public static Date getLastDate(Date date){
Calendar calendar = Calendar.getInstance();
calendar.se