//版本对比
public static boolean compareVersions(String v1, String v2) {
//参数 当前,目标
if (v1 == null || v2 == null || TextUtils.equals(v1, "") || TextUtils.equals(v2, "")) {
return false;
}
String[] s1 = v1.split("\\.");
String[] s2 = v2.split("\\.");
int it = s1.length > s2.length ? s1.length : s2.length;
String[] n1 = Arrays.copyOf(s1, it);
String[] n2 = Arrays.copyOf(s2, it);
for (int i=0;i < it;i++) {
String c1 = n1[i],c2 = n2[i];
if (c1 == null) {
c1 = "0";
}
if (c2 == null) {
c2 = "0";
}
if (!isNumber(c1) || !isNumber(c2)) {
return true;
}
if (Integer.parseInt(c1) != Integer.parseInt(c2)) {
//我在这里直接使用的是不等于
//若是需要对比版本号修改这里
return true;
}
}
return false;
}
//判断字符串是否为纯数字
public static boolean isNumber(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
//Pattern pattern = Pattern.compile("^[0-9]*$");
return pattern.matcher(str).matches();
}
//时间戳转时间
public static String getDateToString(long milSecond) {
if (milSecond > 1000) {
Date date = new Date(milSecond);
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd.hh.mm.ss");
//时间格式为年月日时分秒
//如果只需要判断日期yyyy.MM.dd
return format.format(date);
} else {
return null;
}
}
注意
不管是版本还是时间格式统一为xx.xx.xx
数字.数字.数字
若是字符串内包含其它字符的则返回true
数字.数字.英文.数字=true
1.1.a.4=true
如何判断版本?
boolean = compareVersions(new, old)
new为当前版本或时间
old为目标(服务器内)版本或时间
如何判断时间?
String old = getDateToString(Long.parseLong(时间戳));
String new = getDateToString(System.currentTimeMillis());
boolean = compareVersions(new, old);