代碼如下:
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateIO {
public static void main(String[] args) {
Date date= new DateIO().strToDate("2013-04-01");
String strdate=new DateIO().dateToStr(date);
String srrdate=new DateIO().timestampToStr(System.currentTimeMillis());
Timestamp ts=new DateIO().strToTimestamp(new Date());
}
//String 轉換為 Date
public Date strToDate(String strdate){
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(strdate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("date:"+date);
return date;
}
//Date 轉換為 String
public String dateToStr(Date date){
//年月日****-**-**
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String str = format.format(date);
System.out.println("str:"+str);
//年月日**-*-*
format = DateFormat.getDateInstance(DateFormat.SHORT);
str = format.format(date);
System.out.println(str);
//年月日****-*-*
format = DateFormat.getDateInstance(DateFormat.MEDIUM);
str = format.format(date);
System.out.println(str);
//****年*月*日星期*
format = DateFormat.getDateInstance(DateFormat.FULL);
str = format.format(date);
System.out.println(str);
return str;
}
//Timestamp轉換為String
public String timestampToStr(Long timestamp){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定義格式,不顯示毫秒
String str = df.format(timestamp);
System.out.println(str);
return str;
}
//Date轉換為Timestamp
public Timestamp strToTimestamp(Date date){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = df.format(date);
Timestamp ts = Timestamp.valueOf(time);
System.out.println(ts);
return ts;
}
}