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

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.

This question is related to java date time timestamp java.util.date

The answer is


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;
}

Similar questions with java tag:

Similar questions with date tag:

Similar questions with time tag:

Similar questions with timestamp tag:

Similar questions with java.util.date tag: