import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) throws Exception {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設置日期格式
String time = df.format(new Date());// new Date()為獲取當前系統時間
System.out.println(dateToStamp(time));//將時間轉換為時間戳
String res = dateToStamp(time);
System.out.println(stampToDate(res));//將時間戳轉換為時間
}
/*
* 將時間轉換為時間戳
*/
public static String dateToStamp(String s) throws Exception{
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(s);
long ts = date.getTime();
res = String.valueOf(ts);
return res;
}
/*
* 將時間戳轉換為時間
*/
public static String stampToDate(String s){
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(s);
Date date = new Date(lt);
res = simpleDateFormat.format(date);
return res;
}
}
目錄