2

I am calculating the difference between two timestamps which is in the following format

2013-07-22 05:24:24.77

I am using the following method to calculate the difference between two timestamps

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date resDate = sdf.parse(responseData.getTimestamp().toString());
Date reqDate = sdf.parse(requestData.getTimestamp().toString());
System.out.println("response-->"+responseData.getTimestamp());
System.out.println("request-->"+requestData.getTimestamp());
System.out.println("diff-->"+(resDate.getTime()-reqDate.getTime()));

The difference between two timestamps is negative in the following cases. For example

Response date : 2013-07-22 05:24:24.77

Request date : 2013-07-22 05:24:24.663

Result is :

diff-->-586

it should subtract something like this "770-663" instead it subtracting the timestamp as "77-663".

Can anyone please suggest what changes I should make or is there any other way to do it??

Thanks in advance

1
  • 1
    77 means 77, not 770. (i.e. it is 77 ms past, not 770 ms past). So in your example, request date is after response date and it is normal that the difference is negative. Commented Mar 7, 2014 at 11:21

1 Answer 1

5

SSS in SimpleDateFormat means the number of milliseconds, not fractional second, that is for SimpleDateFormat 663 > 77. But Timestamp.toString formats timestamp in yyyy-mm-dd hh:mm:ss.fffffffff format, where fffffffff is fractional second. Usejava.sql.Timestamp.valueOf(str) for parsing what Timestamp.toString produces

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.