1、获取当天的0点和23:59:59 999,以此类推,可以获取任何时刻。
public static Calendar beginOfDay(Calendar calendar) {
calendar.set(11, 0);
calendar.set(12, 0);
calendar.set(13, 0);
calendar.set(14, 0);
return calendar;
}
public static Calendar endOfDay(Calendar calendar) {
calendar.set(11, 23);
calendar.set(12, 59);
calendar.set(13, 59);
calendar.set(14, 999);
return calendar;
}
2、判断当前时刻是否在时间范围内
/**
* 检测当前时间是否在11:30--13:00之间
*
* @return
*/
public static boolean checkRange() {
Date nowDate = new Date();
Calendar cal11 = Calendar.getInstance();
cal11.setTime(nowDate);
cal11.set(Calendar.HOUR_OF_DAY, 11);
cal11.set(Calendar.MINUTE, 30);
cal11.set(Calendar.SECOND, 0);
cal11.set(Calendar.MILLISECOND, 0);
Calendar cal13 = Calendar.getInstance();
cal13.setTime(nowDate);
cal13.set(Calendar.HOUR_OF_DAY, 13);
cal13.set(Calendar.MINUTE, 0);
cal13.set(Calendar.SECOND, 0);
cal13.set(Calendar.MILLISECOND, 0);
long now = nowDate.getTime();
return cal11.getTime().getTime() <= now && now <= cal13.getTime().getTime();
}
3、获取本周一
public static Date getThisWeekMonday(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// 获得当前日期是一个星期的第几天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
// 获得当前日期是一个星期的第几天
int day = cal.get(Calendar.DAY_OF_WEEK);
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
return cal.getTime();
}
4、给定日期加减天数
private static Date offset(Date date, int calendar, int offset) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(6, offset);
return cal.getTime();
}