- 要点
- 日期计算用Calendar类
- Date与String类型互转用SimpleDateFormat类
- 使用SimpleDateFormat的format()方法实现Date转为String
- 使用SimpleDateFormat的parse()方法实现String转为Date
- 代码
public class DateUtil {
public static String date2Str(Date date, String format) {
String result = "";
SimpleDateFormat sdf = new SimpleDateFormat(format);
if (date != null) {
result = sdf.format(date);
}
return result;
}
public static Date str2Date(String str, String format) throws Exception {
if ("".equals(str) || str == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.parse(str);
}
public static String getCurrentDateStr() throws Exception {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
return sdf.format(date);
}
}