import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;java
/**
* java.util.Date日期类型与字符串类型之间的转换
*/
public class DateStringChange {spa
// 日期转换为固定格式的字符串
public static String dateToString(Date date) {
// 返回值
String res;
// 将日期转换为固定格式的字符串
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
res = sdf.format(date);
// 返回
return res;
}orm
// 字符串类型的日期转换为java.util.Date类型的日期
public static Date stringToDate(String dateStr) {
// 返回值
Date date = null;
// 将字符串的日期转换为java.util.Date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = sdf.parse(dateStr);
} catch (ParseException e) {
System.out.println("转换失败:" + e.getMessage());
}
// 返回
return date;
}字符串
public static void main(String[] args) {
System.out.println(DateStringChange.dateToString(new Date()));
System.out.println(DateStringChange.stringToDate("2015-08-15 19:40:38"));
}get
}string
运行结果:io