Java时间日期和时间戳相互转换

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;
}
 }
原文地址:https://www.cnblogs.com/shenhaha520/p/12619583.html