import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CalendarUtils {
public static final String YYYY_MM = "yyyy-MM";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final String YYYY_MM_DD_Hms = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY_MM_DD_Hmss = "yyyy-MM-dd HH:mm:sss";
public static final String YYYYMM = "yyyyMM";
public static final String YYYYMMDD = "yyyyMMdd";
public static final String YYYYMMDDHHmmss = "yyyyMMddHHmmss";
public static final String YYYYMMDDHHmmsss = "yyyyMMddHHmmsss";
private static final Logger logger = LoggerFactory.getLogger(CalendarUtils.class);
static Calendar calendar = Calendar.getInstance();
public static String doFormatString(Date date, String type) {
String result = null;
try {
if (StringUtils.isNotBlank(type)) {
SimpleDateFormat format = new SimpleDateFormat(type);
result = format.format(date);
} else {
// 默认格式化为yyyy-MM-dd HH:mm:ss
SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD_Hms);
result = format.format(date);
}
} catch (Exception e) {
logger.error("日期格式化异常.");
e.printStackTrace();
}
return result;
}
public static Date doFormatDate(String date, String type) {
Date result = null;
if (StringUtils.isEmpty(type)) {
// 默认格式化为yyyy-MM-dd HH:mm:ss
type = YYYY_MM_DD_Hms;
}
try {
SimpleDateFormat format = new SimpleDateFormat(type);
result = format.parse(date);
} catch (ParseException e) {
logger.error("日期格式化异常.");
e.printStackTrace();
}
return result;
}
public static Date doAddDay(Date date, Integer n) {
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, n);
return calendar.getTime();
}
public static Date doAddMonth(Date date, Integer n) {
calendar.setTime(date);
calendar.add(Calendar.MONTH, n);
return calendar.getTime();
}
public static Date doAddYear(Date date, Integer n) {
calendar.setTime(date);
calendar.add(Calendar.YEAR, n);
return calendar.getTime();
}
}