直接上代码:
我们的业务是查询当天、当周、当月、当季、当年的记录,所以结束时间直接使用当前时间,就不贴了。
// 今天的开始 public static Date getDayStart() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar.getTime(); } // 本周的开始 public static Date getWeekStart() { Calendar calendar = Calendar.getInstance(); calendar.setTime(getDayStartStamp()); int dayofweek = calendar.get(Calendar.DAY_OF_WEEK); if (dayofweek == 1) { dayofweek += 7; } calendar.add(Calendar.DATE, 2 - dayofweek); return calendar.getTime(); } // 本月的开始 public static Date getMonthStart() { Calendar calendar = Calendar.getInstance(); calendar.setTime(getDayStartStamp()); calendar.set(Calendar.DAY_OF_MONTH, 1); return calendar.getTime(); } // 本季的开始 public static Date getQuarterStart() { Calendar calendar = Calendar.getInstance(); calendar.setTime(getDayStartStamp()); int month = calendar.get(Calendar.MONTH); if (month < 4) { calendar.set(Calendar.MONTH, 0); } if (month >= 4) { calendar.set(Calendar.MONTH, 3); } if (month >= 7) { calendar.set(Calendar.MONTH, 6); } if (month >= 10) { calendar.set(Calendar.MONTH, 9); } calendar.set(Calendar.DAY_OF_MONTH, 1); return calendar.getTime(); } // 本年的开始 public static Date getYearStart() { Calendar calendar = Calendar.getInstance(); calendar.setTime(getDayStartStamp()); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.DAY_OF_MONTH, 1); return calendar.getTime(); }