将Java中的java.util.date默认格式转换为Timestamp [英] Convert java.util.date default format to Timestamp in Java

查看:263
本文介绍了将Java中的java.util.date默认格式转换为Timestamp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.date的默认格式类似于"IST 2013星期一5月27日11:46:15".如何将其转换为时间戳并以秒为单位计算相同时间与当前时间之间的时差?

The default format of java.util.date is something like this "Mon May 27 11:46:15 IST 2013". How can I convert this into timestamp and calculate in seconds the difference between the same and current time?

java.util.Date date= new java.util.Date();
Timestamp ts_now = new Timestamp(date.getTime());

上面的代码为我提供了当前时间戳.但是,我不知道如何找到上述字符串的时间戳.

The above code gives me the current timestamp. However, I got no clue how to find the timestamp of the above string.

推荐答案

您可以使用Calendar类转换Date

public long getDifference()
{
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
    Date d = sdf.parse("Mon May 27 11:46:15 IST 2013");

    Calendar c = Calendar.getInstance();
    c.setTime(d);
    long time = c.getTimeInMillis();
    long curr = System.currentTimeMillis();
    long diff = curr - time;    //Time difference in milliseconds
    return diff/1000;
}

这篇关于将Java中的java.util.date默认格式转换为Timestamp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆