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;
}
}
复制代码
Java时间戳与时间的相互转换(只是为了记住才写,望原谅)
最新推荐文章于 2024-01-10 15:58:34 发布