Date和String的相互转化
SimpleDateFormat 1、字符串转Date、String转Date 2、Date转字符串、Date转String |
**
* 字符串和日期转换工具
* @author zeng__000
*
*/
public class DateStringUtil {
/**
* Date类型格式化成String
* @param date 要转换的Date
* @param pattern 以什么格式将Date格式化成String
* @return
*/
public static String dateToString(Date date,String...pattern){
String patn = null;
if (pattern==null || pattern.length==0) {
patn = "yyyy-MM-dd";
}else {
patn = pattern[0];
}
SimpleDateFormat sdf = new SimpleDateFormat(patn);
return sdf.format(date);
}
/**
* String转成Date类型
* @param str 要转的字符串String
* @param pattern 以什么格式将字符串转成Date
* @return
*/
public static Date strToDate(String str,String...pattern){
try {
String patn = null;
if (pattern==null || pattern.length==0) {
patn = "yyyy-MM-dd";
}else {
patn = pattern[0];
}
SimpleDateFormat sdf = new SimpleDateFormat(patn);
return sdf.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
|