I am using the following method to get a difference between two time stamps.
public static long tokenTimeDuration(String loginTime, String expiryTime){
long diff = 0;
Log.i("du_loginTimeFromServer",loginTime);
Log.i("du_expiryTimeFromServer",expiryTime);
DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss a z yyyy");
format.setLenient(false);
Date loginDate = null;
Date expiryDate = null;
try {
loginDate = (Date)format.parse(loginTime);
Log.i("du_loginTimeAfterParsing",format.format(loginDate));
expiryDate = (Date)format.parse(expiryTime);
Log.i("du_expiryTimeAfterParsing",format.format(expiryDate));
Log.i("du_loginTimeInMilliseconds",loginDate.getTime()+"");
Log.i("du_expiryTimeInMilliseconds",expiryDate.getTime()+"");
//in milliseconds
diff = expiryDate.getTime() - loginDate.getTime();
Log.i("du_tokenExpiryDuration", diff + "");
} catch (Exception e) {
Log.i("duEx", e.getMessage());
}
return diff;
}
But while trying to use the method, I'm getting a wrong conversion of dates. And log output for the same as below:
12-05 19:30:45.802: I/du_loginTimeFromServer(16894): Fri Dec 05 14:00:44 PM UTC 2014
12-05 19:30:45.802: I/du_expiryTimeFromServer(16894): Fri Dec 05 17:20:44 PM UTC 2014
12-05 19:30:45.822: I/du_loginTimeAfterParsing(16894): Fri Dec 05 05:30:44 AM IST 2014
12-05 19:30:45.824: I/du_expiryTimeAfterParsing(16894): Fri Dec 05 05:50:44 AM IST 2014
12-05 19:30:45.824: I/du_loginTimeInMilliseconds(16894): 1417737644000
12-05 19:30:45.824: I/du_expiryTimeInMilliseconds(16894): 1417738844000
12-05 19:30:45.824: I/du_tokenExpiryDuration(16894): 1200000
Now sometimes it gives a negative difference even if the expiry time is 4 hours ahead of the login time. Please help me find where am I going wrong.
Update: If I add
format.setTimeZone(TimeZone.getTimeZone("UTC"));
The logcat says:
12-05 22:05:59.903: I/du_loginTimeFromServer(23574): Fri Dec 05 16:35:58 PM UTC 2014
12-05 22:05:59.903: I/du_expiryTimeFromServer(23574): Fri Dec 05 19:55:58 PM UTC 2014
12-05 22:05:59.915: I/du_loginTimeAfterParsing(23574): Fri Dec 05 00:35:58 AM UTC 2014
12-05 22:05:59.918: I/du_expiryTimeAfterParsing(23574): Fri Dec 05 00:55:58 AM UTC 2014
12-05 22:05:59.918: I/du_loginTimeInMilliseconds(23574): 1417739758000
12-05 22:05:59.919: I/du_expiryTimeInMilliseconds(23574): 1417740958000
12-05 22:05:59.919: I/du_tokenExpiryDuration(23574): 1200000
Still not correct.