/**
* 兩個日期相減相差的月份
* @param beginDate
* @param endDate
* @return
*/
public int getDifMonth(Date startDate, Date endDate) {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.setTime(startDate);
end.setTime(endDate);
int result = end.get(Calendar.MONTH) - start.get(Calendar.MONTH);
int month = (end.get(Calendar.YEAR) - start.get(Calendar.YEAR)) * 12;
return Math.abs(month + result);
}
/** * 日期相加減 * @param time * 時間字符串 yyyy-MM-dd HH:mm:ss * @param num * 加的數,-num就是減去 * @return * 減去相應的數量的年的日期 * @throws ParseException */ public static Date yearAddNum(Date time, Integer num) { //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //Date date = format.parse(time); Calendar calendar = Calendar.getInstance(); calendar.setTime(time); calendar.add(Calendar.YEAR, num); Date newTime = calendar.getTime(); return newTime; } /** * * @param time * 時間 * @param num * 加的數,-num就是減去 * @return * 減去相應的數量的月份的日期 * @throws ParseException Date */ public static Date monthAddNum(Date time, Integer num){ //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //Date date = format.parse(time); Calendar calendar = Calendar.getInstance(); calendar.setTime(time); calendar.add(Calendar.MONTH, num); Date newTime = calendar.getTime(); return newTime; } /** * * @param time * 時間 * @param num * 加的數,-num就是減去 * @return * 減去相應的數量的天的日期 * @throws ParseException Date */ public static Date dayAddNum(Date time, Integer num){ //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //Date date = format.parse(time); Calendar calendar = Calendar.getInstance(); calendar.setTime(time); calendar.add(Calendar.DAY_OF_MONTH, num); Date newTime = calendar.getTime(); return newTime; } /** * 獲取本月第一天時間 */public static Date getMonthStartDate(){ Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH,1); return calendar.getTime();}/** * 獲取本月最后一天 * */public static Date getMonthEndDate(){ Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); return calendar.getTime();} /** * 獲取本周的開始時間 */public static Date getBeginWeekDate(){ Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); int dayofweek = cal.get(Calendar.DAY_OF_WEEK); //周日是1 ,周一是 2 ,周二是 3 //所以,當周的第一天 = 當前日期 - 距離周一過了幾天(周一過了0天,周二過了1天, 周日過了6天) // 2 - 周一的(dayofweek:2 )= 0 // 2 - 周二的(dayofweek:3 )= -1 // . // . // 2 - 周日的(dayofweek:1) = 1(這個是不符合的需要我們修改)===》2 - 周日的(dayofweek:1 ==》8 ) = -6 if (dayofweek == 1) { dayofweek += 7; } cal.add(Calendar.DATE, 2 - dayofweek); return cal.getTime();} /** * 本周的結束時間 * 開始時間 + 6天 */public static Date getEndWeekDate(){ Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); int dayofweek = cal.get(Calendar.DAY_OF_WEEK); if (dayofweek == 1) { dayofweek += 7; } cal.add(Calendar.DATE, 8 - dayofweek);//2 - dayofweek + 6 return cal.getTime();}