最近一直写程序分析软件Trace, 所以Trace中的时间戳要处理一下...
经常遇到的一个问题是比较给定格式的时间字符串的先后顺序,由于字符串包含英文月份, e.g. Aug, Jan, May, etc.
所以需要用SimpleDateFormat格式化:
new SimpleDateFormat("MMM dd HH:mm:ss yyyy", Locale.US);
其中要解析英文月份的话必须用java.util.Locale自带的属性Locale.US.
用了三种方法(3种comparer)比较时间前后:
public class TimeComparer {
/**
*
* @param time1 input timestamp No.1
* @param time2 input timestamp No.2
* @param timestampFormat the format object for time stamp
* @return
* if return value is 1 -> time 1 is newer
* value is -1 -> time 2 is newer
* value is 0 -> same timestamps
*/
int timestampCompare(String time1, String time2, SimpleDateFormat timestampFormat) {
int comparer = 3 ;
int rev = 0;
if(time1.equals(time2)) // same
return rev;
try {
Date timestamp1 = timestampFormat.parse(time1);
Date timestamp2 = timestampFormat.parse(time2);
switch (comparer) {
case 1: //Compare 1 - function getTime()
if(timestamp1.getTime() > timestamp2.getTime()) // time1 has more seconds -> time1 is newer
return 1;
else return -1;
case 2: //Compare 2 - function before/after
if(timestamp1.after(timestamp2)) // time 1 is newer
return 1;
else return -1;
case 3: //Compare 3 - function calendar compareTo
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(timestamp1);
cal2.setTime(timestamp2);
if(cal1.compareTo(cal2) > 0) // cal1 is bigger -> cal1 is newer
return 1;
else return -1;
default:
break;
}
} catch (ParseException e) {
e.printStackTrace();
}
return rev;
}
}
另外主函数的测试用例为:
public static void main(String[] args) {
String timestamp1 = "Aug 30 13:12:27 2017";
String timestamp2 = "Aug 28 21:30:05 2017";
//MMM dd hh:mm:ss yyyy
SimpleDateFormat timestampFormat = new SimpleDateFormat("MMM dd HH:mm:ss yyyy", Locale.US);
int rev = new TimeComparer().timestampCompare(timestamp1, timestamp2, timestampFormat);
if(rev > 0)
System.out.println(timestamp1 + " is newer!");
else if(rev < 0)
System.out.println(timestamp2 + " is newer!");
else
System.out.println("Same timestamps!");
}