Reputation: 1764
Say I have 2 strings containing date as follow
String A = 25 Nov 2015 10.50 GMT+6
String B = 25 Nov 2015 10.45 GMT+6
How do I make it so that it is acceptable to have a differences of several minutes between the two date strings? I can't use Selenium to assert between the two strings as it would definitely throw me asserting error.
Upvotes: 1
Views: 95
Reputation: 31878
The methods suggested are nice, though I believe you must be getting these strings from the Date
itself in which case why not try this :
Date d1 = <source for String A>;
Date d2 = <source for String B>;
long diff = d2.getTime() - d1.getTime();
//here are the differences
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
//for your case
if(diffMinutes <= acceptableDifference) //I' fine with it
else //Give me something else
Upvotes: 0
Reputation: 241
YOu can use the below comparator to compare roughly equal dates. You can decide the delta for two dates being equal while instantiating the comparator.
public class RoughlyEqualDates implements Comparator<String> {
int acceptableDelta = 300000; // 5 minutes
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy HH:mm");//choose appropriate format here
RoughlyEqualDates(int deltaInMins){//configurable delta
this.acceptableDelta = deltaInMins*60*1000;
}
public int compare(String date1, String date2) {
long d1,d2;
try {
d1 = format.parse(date1).getTime();
d2 = format.parse(date2).getTime();
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
if(Math.abs(d1-d2)<=acceptableDelta){
return 0;
}else{
return d1>d2?1:-1;
}
}
}
Upvotes: 0
Reputation: 159096
Parse the strings, then compare the milliseconds and apply a threshold.
But first, you have to fix those bad GMT offsets.
String a = "25 Nov 2015 10.50 GMT+6";
String b = "25 Nov 2015 10.45 GMT+6";
// fix bad GMT
a = a.replaceFirst(" GMT\\+(\\d)\\b", " GMT+0$1");
b = b.replaceFirst(" GMT\\+(\\d)\\b", " GMT+0$1");
// parse dates
SimpleDateFormat datefmt = new SimpleDateFormat("d MMM yyyy HH.mm 'GMT'X");
Date dateA = datefmt.parse(a);
Date dateB = datefmt.parse(b);
// detect difference
long diffInMillis = Math.abs(dateA.getTime() - dateB.getTime());
if (diffInMillis < 5 * 60 * 1000) {
// all is good
} else {
// bad: 5 or more minutes apart
}
Upvotes: 2