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-12-11 18:02:43 发布
本文详细介绍了一种使用Java进行日期格式化、时间戳转换的方法。通过实例代码展示了如何将当前系统时间转换为指定格式的字符串,再进一步转换为时间戳,以及如何将时间戳还原为原始时间格式。
60

被折叠的 条评论
为什么被折叠?



