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.
We can convert date to timestamp using the Timestamp class which is present in the SQL package. The constructor of the time-stamp class requires a long value. So data needs to be converted into a long value by using the getTime() method of the date class(which is present in the util package).
The Date/Time API in Java works with the ISO 8601 format by default, which is (yyyy-MM-dd) . All Dates by default follow this format, and all Strings that are converted must follow it if you're using the default formatter.
No time data is kept. In fact, the date is stored as milliseconds since the 1st of January 1970 00:00:00 GMT and the time part is normalized, i.e. set to zero. Basically, it's a wrapper around java. util.
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;
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With