假设我有2个包含日期的字符串,如下所示
print tmp_crd.data
>>> [-9999. -9999. -9999. ..., -9999. -9999. -9999.]
如何才能使两个日期字符串之间有几分钟的差异?我无法使用 Selenium 在两个字符串之间断言,因为它肯定会让我断言错误。
答案 0 :(得分:2)
解析字符串,然后比较毫秒并应用阈值。
但首先,你必须修复那些糟糕的GMT补偿。
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
}
答案 1 :(得分:0)
你可以使用下面的比较器来比较大致相等的日期。在实例化比较器时,您可以确定两个日期的增量相等。
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;
}
}
}
答案 2 :(得分:0)
建议的方法很好,但我相信你必须从Date
本身获取这些字符串,在这种情况下为什么不试试这个:
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