1. String Date 相互转化
String->java.util.Date
public void StrToDate() throws ParseException{
String str = "2014-11-23 02:50:12";
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = sdf.parse(str);
System.out.println(date);
}
java.util.Date->String
public void dateToStr(){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss");
String str = sdf.format(date);
System.out.println(str);
str = sdf2.format(date);
System.out.println(str);
}
2.String Timestamp 相互转化
String->Timestamp
public void stringToTimestamp(){
Timestamp ts = new Timestamp(System.currentTimeMillis());
//String的类型必须形如: yyyy-mm-dd hh:mm:ss[.f...] 这样的格式,中括号表示可选,否则报错!
String str = "2014-11-23 02:59:11";
ts = Timestamp.valueOf(str);
System.out.println(ts);
}
Timestamp->String
public void timestampToString(){
String str = "";
Timestamp ts = new Timestamp(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//方法一
str = sdf.format(ts);
System.out.println(str);
//方法二
str = ts.toString();
System.out.println(str);
}
3. Timestammp Date之间想到转化
Timestamp->java.util.Date
public void timestampToDate(){
Timestamp ts = new Timestamp(System.currentTimeMillis());
Date date = new Date();
date = ts;
System.out.println(date);
}
java.util.Date->Timestamp
public void dateToTimestamp(){
Timestamp ts = new Timestamp(new Date().getTime());
System.out.println(new Date());
System.out.println(ts);
}
4.java.util.Date(包含年月日时分秒) 与java.sql.Date(只包含年月日)
java.util.Date(包含年月日时分秒) 与java.sql.Date(只包含年月日)
public void UtilDateToSqlDate(){
java.util.Date dateU = new java.util.Date();
java.sql.Date dateS = new java.sql.Date(dateU.getTime());
System.out.println(dateS);
}
public void SqlDateToUtilDate(){
java.sql.Date dateS = new java.sql.Date(2014, 11, 23);
java.util.Date dateU = new java.util.Date(dateS.getTime());
System.out.println(dateU);
}