1. 字符串转换为日期
public Date parseDate(String strDate,String pattern){
if(strDate==null || pattern==null || "".equals(strDate.trim()) ||"".equals(pattern.trim()) ){
throw new IllegalArgumentException("字符串或日期格式为空");
}
Date date = null;
try{
SimpleDateFormat parser = new SimpleDateFormat(pattern);
date=parser.parse(strDate);
}catch (ParseException e) {
System.out.println("格式化失败" + e.getMessage());
}
return date;
}
2. 日期格式化为字符串
public String format(Date date, String pattern) {
if(date==null){
return "";
}
if (date == null || pattern == null || "".equals(pattern.trim())){
throw new IllegalArgumentException("日期或字符串格式为空");
}
String str = null;
try {
SimpleDateFormat parser = new SimpleDateFormat(pattern);
str = parser.format(date);
} catch (Exception e) {
System.out.println("不能转换" + e.getMessage());
}
return str;
}
3. 把一种格式的日期字符串格式化成另一种格式的日期字符串
public String format (String str, String oldP, String newP) {
if (str == null || "".equals(str.trim()) || oldP == null
|| "".equals(oldP.trim()) || newP == null
|| "".equals(newP.trim())){
throw new IllegalArgumentException("不能为空");
}
return format(parseDate(str,oldP),newP);
}