将java.util.date默认格式转换为Java中的Timestamp

swa*_*eek 8 java time timestamp date java.util.date

java.util.date的默认格式是这样的"Mon May 27 11:46:15 IST 2013"​​.如何将其转换为时间戳并以秒计算相同和当前时间之间的差异?

java.util.Date date= new java.util.Date();
Timestamp ts_now = new Timestamp(date.getTime());
Run Code Online (Sandbox Code Playgroud)

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

Rah*_*ate 12

您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)


Kis*_*ore 8

最好的

String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date); 
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;
Run Code Online (Sandbox Code Playgroud)