import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Test{
public static void main(String[] args) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(new Date()));
//獲取當前時間戳,也可以是你自已給的一個隨機的或是別人給你的時間戳(一定是long型的數據)
long timeStamp = System.currentTimeMillis();
logger.info("timeStamp:"+timeStamp);
//這個是你要轉成后的時間的格式
SimpleDateFormat sdff=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 時間戳轉換成時間
String sd = sdff.format(new Date());
System.out.println("sd:"+sd);//打印出你要的時間
dateToStamp(sd);
System.out.println("dateToStamp(sd):"+dateToStamp(sd));
long time = 30*60*1000;//30分鍾
Date beforeDate = new Date((new Date()).getTime() - time);//30分鍾前的時間
System.out.println("beforeDate:"+beforeDate);
//時間格式轉換
SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM d HH:mm:ss 'CST' yyyy", Locale.ENGLISH);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format1 = sdf2.format(sdf1.parse(beforeDate.toString()));
System.out.println("format1:"+format1);
System.out.println("beforeDate:"+dateToStamp(format1));
}
//將時間轉換為時間戳
public static String dateToStamp(String s) throws ParseException {
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);
logger.info("res:"+res);
return res;
}
}