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

125,469

Solution 1

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

Solution 2

Best one

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;
Share:
125,469
swateek
Author by

swateek

Foodie | Traveller | Technologist | blogs | lazy reader | Dog Lover | Wants to pet a baby elephant |

Updated on October 24, 2020

Comments

  • swateek
    swateek over 3 years

    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.

  • swateek
    swateek almost 11 years
    How did it convert the string I passed?
  • swateek
    swateek almost 11 years
    I want to convert "Mon May 27 11:46:15 IST 2013" this string into timestamp. And find the difference between it and the current time..that too in seconds.
  • swateek
    swateek almost 11 years
    Am s database freak...Java is confusing me.
  • swateek
    swateek almost 11 years
    While am trying to convert "Mon May 27 11:46:15 IST 2013" string to date. It gives me an unparsable string exception. Any idea how can I go about?
  • Rahul Bobhate
    Rahul Bobhate almost 11 years
    @Swat: Updated the answer.
  • swateek
    swateek almost 11 years
    thanks a lot @Rahul . I actually combined your answer with Salem's answer above to get this right. Thanks! :)
  • swateek
    swateek almost 11 years
    Thank you! I used your answer along with @Rahul 's to get this right.
  • swateek
    swateek almost 11 years
    Thanks @Nidhin, I found the work around with Salem and Rahul's answer below. Appreciate your quick help. :)