// 获取某日期的日号
public int getDate(Date d) {
Calendar ca = Calendar.getInstance();
ca.setTime(d);
int days = ca.get(Calendar.DATE);
return days;
}
// 给定日期的前/后n天
// n=-1表示前一天,n=1表示后一天
public Date getDateForDayNum(Date date, int n) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.add(Calendar.DAY_OF_MONTH, n);
Date d = ca.getTime();
return d;
}
// 给定日期的前/后n月
// n=-1表示前一月,n=1表示后一月
public Date getDateForMonthNum(Date date, int n) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.add(Calendar.MONTH, n);
Date d = ca.getTime();
return d;
}
//前/后某月、前/后某日的日期
public Date getDateForMonthNum(Date date, int Month,int day) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.add(Calendar.MONTH, Month);
ca.add(Calendar.DAY_OF_MONTH, day);
Date d = ca.getTime();
return d;
}
// 给定日期的前/后n年
// n=-1表示前一年,n=1表示后一年
public Date getDateForYearNum(Date date, int n) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.add(Calendar.YEAR, n);
Date d = ca.getTime();
return d;
}
// 给定日期的前/后n小时
// n=-1表示前一小时,n=1表示后一小时
public Date getDateForHourNum(Date date, int n) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.add(Calendar.HOUR, n);
Date d = ca.getTime();
return d;
}
// 某年某月的最后一天
public Date getLastDay(Date date) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.roll(Calendar.MONTH, 1);// 向后回滚一个月
ca.set(Calendar.DATE, 0);
Date time = ca.getTime();
return time;
}
// 某年某月的有多少天
public int getDateNumForDate(Date date) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.roll(Calendar.MONTH, 1);
ca.set(Calendar.DATE, 0);
return ca.get(Calendar.DATE);
}
// 某年某月是星期几(周日返回0,周一到周六就是1-6)
public int getWeek(Date date) {
Calendar ca = Calendar.getInstance();
int week = ca.get(Calendar.DAY_OF_WEEK) - 1;// 设置
return week;
}
网友评论