这里涉及到Calendar的相关知识。
public class DateUtil {
private static SimpleDateFormat format = new SimpleDateFormat();
/**
* 日期格式:yyyyMMddHHmmssSSS
*/
public static String yyyyMMddHHmmssSSS = "yyyyMMddHHmmssSSS";
/**
* 日期格式:yyyyMMddHHmmss
*/
public static String yyyyMMddHHmmss = "yyyyMMddHHmmss";
/**
* 日期格式:yyMMdd
*/
public static String yyMMdd = "yyMMdd";
/**
* 日期格式: yyyy
*/
public static final String yyyy = "yyyy";
/**
* 日期格式: MM
*/
public static final String MM = "MM";
/**
* 日期格式: yyyyMM
*/
public static final String yyyyMM = "yyyyMM";
/**
* 日期格式: yyyy/MM/dd
*/
public static final String yyyy/MM/dd = "yyyy/MM/dd";
/**
* 日期格式: yyyyMMdd
*/
public static final String yyyyMMdd = "yyyyMMdd";
/**
* 日期格式: yyyy/MM/dd HH:mm:ss
*/
public static final String yyyy/MM/dd HH:mm:ss = "yyyy/MM/dd HH:mm:ss";
/**
* 日期格式:yyyy-MM-dd
*/
public static final String yyyy-MM-dd = "yyyy-MM-dd";
/**
* 日期格式:yyyy年MM月dd日
*/
public static final String yyyy_MM_dd_ = "yyyy年MM月dd日";
/**
* 时间格式:HH:mm
*/
public static final String HH_mm = "HH:mm";
/**
* 时间格式:HHmm
*/
public static final String HHmm = "HHmm";
/**
* 日期时间格式:yyyy-MM-dd HH:mm
*/
public static final String yyyy-MM-dd_HH_mm = "yyyy-MM-dd HH:mm";
/**
* 日期时间格式:yyyy-MM-dd HH:mm:ss
*/
public static final String yyyy-MM-dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";
/**
* 日期时间格式:yyyy/MM/dd HHmm
*/
public static final String yyyy_MM_dd_HHmm = "yyyy/MM/dd HHmm";
/**
* 日期时间格式:dd/MM/yy
*/
public static final String dd_MM_yy = "dd/MM/yy";
/**
* 日期时间格式:dd-MM-yy
*/
public static final String dd-MM-yy = "dd-MM-yy";
/**
* 日期时间格式:dd/MM/yyyy
*/
public static final String dd_MM_yyyy = "dd/MM/yyyy";
/**
* 日期时间格式:yyyy.MM.dd
*/
public static final String yyyy_MM_dd = "yyyy.MM.dd";
/**
* 方法一
* 取得日期字符串
*/
public static String formatDate(Date date, String pattern) {
if (date == null) {
return "";
}
format.applyPattern(pattern);
return format.format(date);
}
/**
* 方法二
* 取得日期字符串
*/
public static Date parseDate(String strDate, String pattern) throws SystemException {
format.applyPattern(pattern);
try {
return format.parse(strDate);
} catch (ParseException e) {
throw new SystemException(e, e.getMessage());
}
}
/*回滚方法*/
/**
* 向前或是向后滚动年
*/
public static Date rollYear(Date date, int rollCount) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.roll(Calendar.YEAR, rollCount);
return ca.getTime();
}
/**
* 向前或者向后滚动月份 正数像前滚 负数向后滚
*/
public static Date rollMonth(Date date, int rollCount) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.add(Calendar.MONTH, rollCount);
return ca.getTime();
}
}