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;
Author by
swateek
Foodie | Traveller | Technologist | blogs | lazy reader | Dog Lover | Wants to pet a baby elephant |
Updated on October 24, 2020Comments
-
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 almost 11 yearsHow did it convert the string I passed?
-
swateek almost 11 yearsI 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 almost 11 yearsAm s database freak...Java is confusing me.
-
swateek almost 11 yearsWhile 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 almost 11 years@Swat: Updated the answer.
-
swateek almost 11 yearsthanks a lot @Rahul . I actually combined your answer with Salem's answer above to get this right. Thanks! :)
-
swateek almost 11 yearsThank you! I used your answer along with @Rahul 's to get this right.
-
swateek almost 11 yearsThanks @Nidhin, I found the work around with Salem and Rahul's answer below. Appreciate your quick help. :)