Convert java.util.date default format to Timestamp in Java

swateek picture swateek · May 27, 2013 · Viewed 124.8k times · Source

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.

Answer

Rahul Bobhate picture Rahul Bobhate · May 27, 2013

You can use the Calendar class to convert 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;
}