I am trying to compare received date of an email(date object) with a date(String) in a JSONObject. The two dates are going to be of different Timezones with a difference of 1 hour.
My scenario is that I'll have to get the exact difference between them in seconds and if the difference is +/- 10 seconds, I would have found a match. For this purpose, I decided to convert the both into 'UTC' and then do a difference. Here is my code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String MsgDtStr = sdf.format(messagesToBeProcessed.getReceivedDate());
Date MsgDt = sdf.parse(MsgDtStr);
Date ObjDt = sdf.parse((JsonObj.get("date").toString()));
int DiffInSecs = (int) (ObjDt.getTime() - MsgDt.getTime()) / 1000 % 60;
if (DiffInSecs >= -10 && DiffInSecs <= 10) {
System.out.println("Found a match!");
MatchedList.add(i);
}
This seems to give me the correct result. The mails that are supposed to match with the json objects match. i.e the difference is +/- 10 seconds. However, when I try to print the dates and DiffInSecs
after the above logic, I get values like this:
date in object: 2017-06-22 19:47:25
date in message: 2017-06-22 23:47:30
DiffInSecs: -5
........
date in object: 2017-06-22 17:50:38
date in message: 2017-06-22 21:50:39
DiffInSecs: -1
I see that there is a difference of 4 hours between the times. Now I am confused how my logic is even working. Any explanations on this? and is my approach to the problem even correct?
These are my sample date values of a mail and a jsonobject that I should work with and these should match: (How can I achieve this in any way, not just the aproach I posted)
messagesToBeProcessed[i].getReceivedDate(): Thu Jun 22 01:03:13 CDT 2017
messagesToBeProcessed[i].getReceivedDate().getTime(): 1498111393000
Obj.get('date'): 2017-06-22 02:03:03
ObjDt.getTime(): 1498096983000
EDIT:
As pointed out by JBNizet in his comment, I'll need to remove the %60
to get the exact difference in seconds.
Okay, now I feel sticking to the old API doesn't make sense. Now my date in the message object is not being converted to UTC anymore like I posted in the above result. I am not sure why it worked earlier and doesn't anymore (Any explanations/comments on this are welcome). As pointed out by Hugo in his answer, using new Java.Time API is better.
Hope this thread helps someone find way in the future.