java时间与时间戳互转

java中时间精确到毫秒级,所以需求时间需要 除以1000

//将时间转换为时间戳
    public static String dateToStamp(String s) throws Exception {
        String res;<br>         //设置时间格式,将该时间格式的时间转换为时间戳
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long time = date.getTime();
        res = String.valueOf(time);
        return res;
    }
//将时间戳转换为时间
    public static String stampToTime(String s) throws Exception{
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);<br>         //将时间戳转换为时间
        Date date = new Date(lt);<br>         //将时间调整为yyyy-MM-dd HH:mm:ss时间样式
        res = simpleDateFormat.format(date);
        return res;
    }

后天调用代码为,通过除以1000获取到日期和时间的时间戳

//getTime()方法是获取当前时间的时间戳,但是得到的时间不是当前时间<br>Long s = new Date().getTime()/1000;
String s1 = TimeFormatUtil.stampToTime(String.valueOf(s));

需要转换,先转换为"yyyy-MM-dd HH:mm:ss"这个格式的时间,然后在将这个时间转换为时间戳

//先将当前时间转换为习惯时间
String date = TimeFormatUtil.timeToStamp(new Date());
//将习惯时间转换为时间戳
String time = TimeFormatUtil.dateToStamp(date);

转自:https://www.cnblogs.com/li-yi-learn/p/9036982.html

原文地址:https://www.cnblogs.com/cnwy/p/14737636.html